Java Database Connectivity With MySQL

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

Java Database Connectivity with MySQL

To connect Java application with the MySQL database, we need to


follow 5 following steps.

In this example we are using MySql as the database. So we need to


know following informations for the mysql database:

1. Driver class: The driver class for the mysql database


is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API,
mysql is the database, localhost is the server name on which mysql
is running, we may also use IP address, 3306 is the port number
and sonoo is the database name. We may use any database, in such
case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of
installing the mysql database. In this example, we are going to use
root as the password.

Let's first create a table in the mysql database, but before creating table,
we need to create database first.

1. create database sonoo;  
2. use sonoo;  
3. create table emp(id int(10),name varchar(40),age int(3));  

Example to Connect Java Application with mysql database

In this example, sonoo is the database name, root is the username and
password both.

import java.sql.*;  
class MysqlCon{  
public static void main(String args[]){  
try{  
Class.forName("com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection(  
"jdbc:mysql://localhost:3306/sonoo","root","root");  
//here sonoo is database name, root is username and password  
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery("select * from emp");  
while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3))
;  
con.close();  
}catch(Exception e){ System.out.println(e);}  
}  
}  

JDBC SQL INSERT Query Example


In previous posts, we have learned about types of JDBC drivers and
the how to make database connection using JDBC and then how to
execute SELECT Query. Let’s move forward. In this example I am
picking up execution of SQL INSERT queries using JDBC.
SQL INSERT query are executed to push/store data stored in relational
databases. It requires following steps:
1) Make a database connection
2) Execute the SQL INSERT Query
Pre-requisites include setting up a database schema and creating a table
at least.
CREATE SCHEMA 'JDBCDemo' ;
 
CREATE  TABLE 'JDBCDemo'.'EMPLOYEE'
(
  'ID' INT NOT NULL DEFAULT 0 ,
  'FIRST_NAME' VARCHAR(100) NOT NULL ,
  'LAST_NAME' VARCHAR(100) NULL ,
  'STAT_CD' TINYINT NOT NULL DEFAULT 0
);
Let’s write above steps in code:

1) Make a database connection


Though we have already learned about it in making JDBC connection,
lets recap with this simple code snippet.
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
    .getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");

2) Execute the SQL INSERT Query


This is the main step and core part in ths post. It requires creating a
Statement object and then using it’s execute() method.
Statement stmt = connection.createStatement();
stmt.execute("INSERT INTO EMPLOYEE
(ID,FIRST_NAME,LAST_NAME,STAT_CD) VALUES (1,'Lokesh','Gupta',5)");
Above statement will execute an insert statement in database we are
connected to.
Let’s see the whole code in working.
package com.howtodoinjava.jdbc.demo;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
 
public class InsertDataDemo {
    public static void main(String[] args) {
        Connection connection = null;
        Statement stmt = null;
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root",
"password");
             
            stmt = connection.createStatement();
            stmt.execute("INSERT INTO EMPLOYEE
(ID,FIRST_NAME,LAST_NAME,STAT_CD) "
                                + "VALUES (1,'Lokesh','Gupta',5)");
        }
        catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                stmt.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Transaction Management in JDBC

Transaction represents a single unit of work.

The ACID properties describes the transaction management well. ACID


stands for Atomicity, Consistency, isolation and durability.
Atomicity means either all successful or none.

Consistency ensures bringing the database from one consistent state to


another consistent state.

Isolation ensures that transaction is isolated from other transaction.

Durability means once a transaction has been committed, it will remain


so, even in the event of errors, power loss etc.

Advantage of Transaction Mangaement

fast performance It makes the performance fast because database is hit


at the time of commit.

In JDBC, Connection interface provides methods to manage


transaction.

Method Description

void setAutoCommit(boolean It is true by default means each transaction


status) is committed by default.
void commit() commits the transaction.
void rollback() cancels the transaction.

Simple example of transaction management in jdbc using Statement

Let's see the simple example of transaction management using


Statement.

import java.sql.*;  
class FetchRecords{  
public static void main(String args[])throws Exception{  
Class.forName("oracle.jdbc.driver.OracleDriver");  
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localho
st:1521:xe","system","oracle");  
con.setAutoCommit(false);    
Statement stmt=con.createStatement();  
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");  
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");  
con.commit();  
con.close();  
}}  

If you see the table emp400, you will see that 2 records has been added.

PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is


used to execute parameterized query.

Let's see the example of parameterized query:

1. String sql="insert into emp values(?,?,?)";  

As you can see, we are passing parameter (?) for the values. Its value
will be set by calling the setter methods of PreparedStatement.
Why use PreparedStatement?

Improves performance: The performance of the application will be


faster if you use PreparedStatement interface because query is compiled
only once.

How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return


the object of PreparedStatement. Syntax:

1. public PreparedStatement prepareStatement(String query)throws 
SQLException{}  
Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:

Method Description

public void setInt(int paramIndex, sets the integer value to the given
int value) parameter index.

public void setString(int sets the String value to the given


paramIndex, String value) parameter index.

public void setFloat(int sets the float value to the given parameter
paramIndex, float value) index.

public void setDouble(int sets the double value to the given


paramIndex, double value) parameter index.

public int executeUpdate() executes the query. It is used for create,


drop, insert, update, delete etc.
public ResultSet executeQuery() executes the select query. It returns an
instance of ResultSet.

Example of PreparedStatement interface that inserts the record

First of all create table as given below:

1. create table emp(id number(10),name varchar2(50));  

Now insert records in this table by the code given below:

import java.sql.*;  
class InsertPrepared{  
public static void main(String args[]){  
try{  
Class.forName("oracle.jdbc.driver.OracleDriver");  
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localho
st:1521:xe","system","oracle");  
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)
");  
stmt.setInt(1,101);//1 specifies the first parameter in the query  
stmt.setString(2,"Ratan");  
int i=stmt.executeUpdate();  
System.out.println(i+" records inserted");  
con.close();  
}catch(Exception e){ System.out.println(e);}   
}  
}  
Java CallableStatement Interface

CallableStatement interface is used to call the stored procedures and


functions.
We can have business logic on the database by the use of stored
procedures and functions that will make the performance better because
these are precompiled.

Suppose you need the get the age of the employee based on the date of
birth, you may create a function that receives date as the input and
returns age of the employee as the output.

What is the difference between stored procedures and functions.

The differences between stored procedures and functions are given


below:

Stored Procedure Function

is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.

may return 0 or more values. may return only one values.

We can call functions from the Procedure cannot be called from


procedure. function.

Procedure supports input and output Function supports only input


parameters. parameter.

Exception handling using try/catch Exception handling using try/catch


block can be used in stored can't be used in user defined
procedures. functions.
How to get the instance of CallableStatement?

The prepareCall() method of Connection interface returns the instance of


CallableStatement. Syntax is given below:

1. public CallableStatement prepareCall("{ call procedurename(?,?...
?)}");  

The example to get the instance of CallableStatement is given below:

1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}
");  

It calls the procedure myprocedure that receives 2 arguments.

Full example to call the stored procedure using JDBC

To call the stored procedure, you need to create it in the database. Here,
we are assuming that stored procedure looks like this.

1. create or replace procedure "INSERTR"  
2. (id IN NUMBER,  
3. name IN VARCHAR2)  
4. is  
5. begin  
6. insert into user420 values(id,name);  
7. end;  
8. /     

The table structure is given below:

1. create table user420(id number(10), name varchar2(200));  

In this example, we are going to call the stored procedure INSERTR that
receives id and name as the parameter and inserts it into the table
user420. Note that you need to create the user420 table as well to run
this application.
import java.sql.*;  
public class Proc {  
public static void main(String[] args) throws Exception{   
Class.forName("oracle.jdbc.driver.OracleDriver");  
Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");  
stmt.setInt(1,1011);  
stmt.setString(2,"Amit");  
stmt.execute();   
System.out.println("success");  
}  
}  

Now check the table in the database, value is inserted in the user420
table.

JAVA JDBC – Save, Retrieve And Update Image To MySQL


Database
However, it is not practical to save image in database because image size
is big and resources of databases servers are very costly. The most
famous way is store image inside a folder and save image path to
database. However, sometimes you may want to save image to database.

WHAT IS BLOB TYPE?


You must know what is BLOB Type. BLOB (Binary Large Objects)
Type is used to define column in table that store picture. There is no way
insert picture directly in the database instead it you need to convert
image into binary data type then store that binary value to database.
There are 4 types of BLOB that hold binary data in different sizes. You
can choose one of the type according to your picture size while creating
table.
TYPE SIZE
TINYBLOB 255 Bytes
BLOB 64 KB
MEDIUMBLOB 16 MB
LONGBLOB 4 GB

Programming Example
We have a database STOREDB and a Table ITEM inside it. We need to
add an extra column SavePic for storing image in it. Here is a JDBC
program for adding extra BLOB Type column in ITEM table.

STEP 1 : Adding Extra column SavePic with BLOB type in table Item.
package ImageTutorial;

import java.sql.*;

public class AddBlobColumn

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String dburl = "jdbc:mysql://localhost/STOREDB";

static final String dbuser = "root";

static final String dbpass = "root";


public static void main(String[] args)

Connection con = null;

Statement stmt = null;

try

//Step 1 : Connecting to Server

con = DriverManager.getConnection(dburl, dbuser, dbpass);

//Step 2 : Initialize Statement

stmt=con.createStatement();

//Step 3 : SQL Query

//Add New Column SavePic

String query="ALTER TABLE ITEM ADD SavePic BLOB";

//Step 4 : Run Query


stmt.executeUpdate(query);

System.out.println("Column SavePic with BLOB Datatype is


added Successfully");

catch (SQLException e)

System.err.println("Cannot connect ! ");

e.printStackTrace();

finally {

System.out.println("Closing the connection.");

if (con != null) try { con.close(); } catch (SQLException


ignore) {}

}
Output
Column SavePic with BLOB Datatype is added Successfully
Closing the connection.
_
 

STEP 2: Inserting Picture to Table


package ImageTutorial;

import java.sql.*;

import java.io.*;

public class InsertImage

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String dburl = "jdbc:mysql://localhost/STOREDB";

static final String dbuser = "root";

static final String dbpass = "root";

public static void main(String[] args) throws Exception, IOException,


SQLException

Connection con = null;


Statement stmt = null;

FileInputStream fs=null;

PreparedStatement ps=null;

try

//Step 1 : Connecting to server and database

con = DriverManager.getConnection(dburl, dbuser, dbpass);

File f=new
File("/home/prashant/Documents/image/mainjava.jpg");

fs=new FileInputStream(f);

ps= con.prepareStatement("INSERT INTO


ITEM(PRODUCT,PRICE,SavePic) VALUES(?,?,?)");

ps.setString(1, "MainJava Logo");

ps.setString(2, "900");

ps.setBinaryStream(3,fs,(int)f.length());

ps.executeUpdate();
System.out.println("Image Stored Successfully");

catch (SQLException e)

System.err.println("Cannot connect ! ");

e.printStackTrace();

finally {

System.out.println("Closing the connection.");

ps.close();

fs.close();

if (con != null) try { con.close(); } catch (SQLException


ignore) {}

}
}

Output
Image Stored Successfully
Closing the connection.
_

RETRIEVE IMAGE FROM MYSQL DATABASE


Programming Example
package ImageTutorial;

import java.sql.*;

import java.io.*;
public class RetrieveImage

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String dburl = "jdbc:mysql://localhost/STOREDB";

static final String dbuser = "root";

static final String dbpass = "root";

public static void main(String[] args) throws Exception, IOException,


SQLException

Connection con = null;

FileOutputStream fs=null;

PreparedStatement ps=null;

try

//Step 1 : Connecting to server and database

con = DriverManager.getConnection(dburl, dbuser, dbpass);


ps= con.prepareStatement("SELECT * FROM ITEM WHERE
SavePic IS NOT NULL");

ResultSet rset=ps.executeQuery();

byte b[];

Blob blob;

int i=1;

while(rset.next())

i++;

System.out.print("ID: " + rset.getInt(1));

System.out.print(" Product : "+rset.getString(2));

System.out.println(" Price : "+rset.getString(3));

File f=new
File("/home/prashant/Documents/image/mainjava " + i + ".jpg");

fs=new FileOutputStream(f);

blob=rset.getBlob("SavePic");

b=blob.getBytes(1, (int)blob.length());
fs.write(b);

catch (SQLException e)

System.err.println("Cannot connect ! ");

e.printStackTrace();

finally {

System.out.println("Closing the connection.");

ps.close();

fs.close();

if (con != null) try { con.close(); } catch (SQLException


ignore) {}

}
}

Output
ID: 12 Product : MainJava Logo Price : 900
Closing the connection.
_
When you visit the folder location you will see all the images are stored
there from database. In my example you can see all your image in this
path.

/home/prashant/Documents/image/
 

You might also like