Java Database Connectivity With MySQL
Java Database Connectivity With MySQL
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));
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);}
}
}
Method Description
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
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?
1. public PreparedStatement prepareStatement(String query)throws
SQLException{}
Methods of PreparedStatement interface
Method Description
public void setInt(int paramIndex, sets the integer value to the given
int value) parameter index.
public void setFloat(int sets the float value to the given parameter
paramIndex, float value) index.
1. create table emp(id number(10),name varchar2(50));
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
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.
must not have the return type. must have the return type.
1. public CallableStatement prepareCall("{ call procedurename(?,?...
?)}");
1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}
");
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. /
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.
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.*;
try
stmt=con.createStatement();
catch (SQLException e)
e.printStackTrace();
finally {
}
Output
Column SavePic with BLOB Datatype is added Successfully
Closing the connection.
_
import java.sql.*;
import java.io.*;
FileInputStream fs=null;
PreparedStatement ps=null;
try
File f=new
File("/home/prashant/Documents/image/mainjava.jpg");
fs=new FileInputStream(f);
ps.setString(2, "900");
ps.setBinaryStream(3,fs,(int)f.length());
ps.executeUpdate();
System.out.println("Image Stored Successfully");
catch (SQLException e)
e.printStackTrace();
finally {
ps.close();
fs.close();
}
}
Output
Image Stored Successfully
Closing the connection.
_
import java.sql.*;
import java.io.*;
public class RetrieveImage
FileOutputStream fs=null;
PreparedStatement ps=null;
try
ResultSet rset=ps.executeQuery();
byte b[];
Blob blob;
int i=1;
while(rset.next())
i++;
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)
e.printStackTrace();
finally {
ps.close();
fs.close();
}
}
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/