JDBC
JDBC
JDBC
Let's first create a table in the mysql database, but before creating table, we need to
create database first.
In this example, sonoo is the database name, root is the username and password
both.
1. class MysqlCon{
2. public static void main(String args[]){
3. try{
4. Class.forName("com.mysql.jdbc.Driver");
5. Connection con=DriverManager.getConnection(
6. "jdbc:mysql://localhost:3306/sonoo","root","root");
7. //here sonoo is database name, root is username and password
8. Statement stmt=con.createStatement();
9. ResultSet rs=stmt.executeQuery("select * from emp");
10.while(rs.next())
11.System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
12.con.close();
13.}catch(Exception e){ System.out.println(e);}
14.}
15.}
download this example
The above example will fetch all the records of emp table.
2) Set classpath:
Connection interface
A Connection is a session between a Java application and a database. It helps to
establish a connection with the database.
The Connection interface provide many methods for transaction management like
commit(), rollback(), setAutoCommit(), setTransactionIsolation(), etc.
4) public void commit(): saves the changes made since the previous
commit/rollback is permanent.
5) public void rollback(): Drops all changes made since the previous
commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources
immediately.
There are some common Connection interface constant fields that are present in
the Connect interface. These fields specify the isolation level of a transaction.
DriverManager class
The DriverManager class is the component of JDBC API and also a member of
the java.sql package. The DriverManager class acts as an interface between users
and drivers.
It keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver.
It contains all the appropriate methods to register and deregister the database driver
class and to create a connection between a Java application and the database.
The DriverManager class maintains a list of Driver classes that have registered
themselves by calling the method DriverManager.registerDriver().
Statement interface
The Statement interface provides methods to execute queries with the database.
The statement interface is a factory of ResultSet i.e. it provides factory method to
get the object of ResultSet.
Let’s see the simple example of Statement interface to insert, update and delete the
record.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5.
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521
:xe","system","oracle");
6. Statement stmt=con.createStatement();
7.
8. //stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
9.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing
either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as updatable by:
1.
2. ResultSet.CONCUR_UPDATABLE);
3) public boolean first(): is used to move the cursor to the first row
in result set object.
4) public boolean last(): is used to move the cursor to the last row in
result set object.
Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521
:xe","system","oracle");
7.
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Res
ultSet.CONCUR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
9.
10.//getting the record of 3rd row
11.rs.absolute(3);
12.System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
13.
14.con.close();
15.}}
PreparedStatement interface
As you can see, we are passing parameter (?) for the values. Its value will be set by
calling the setter methods of PreparedStatement.
31.3M
698
1.
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521
:xe","system","oracle");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10.stmt.setInt(1,101);//1 specifies the first parameter in the query
11.stmt.setString(2,"Ratan");
12.
13.int i=stmt.executeUpdate();
14.System.out.println(i+" records inserted");
15.
16.con.close();
17.
18.}catch(Exception e){ System.out.println(e);}
19.
20.}
21.}
download this example
Example of PreparedStatement interface that updates the record
1.
1. import java.sql.*;
2. import java.io.*;
3. class RS{
4. public static void main(String args[])throws Exception{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521
:xe","system","oracle");
7.
8. PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");
9.
10.BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
11.
12.do{
13.System.out.println("enter id:");
14.int id=Integer.parseInt(br.readLine());
15.System.out.println("enter name:");
16.String name=br.readLine();
17.System.out.println("enter salary:");
18.float salary=Float.parseFloat(br.readLine());
19.
20.ps.setInt(1,id);
21.ps.setString(2,name);
22.ps.setFloat(3,salary);
23.int i=ps.executeUpdate();
24.System.out.println(i+" records affected");
25.
26.System.out.println("Do you want to continue: y/n");
27.String s=br.readLine();
28.if(s.startsWith("n")){
29.break;
30.}
31.}while(true);
32.
33.con.close();
34.}}
Java ResultSetMetaData Interface
The metadata means data about data i.e. we can get further information from the
data.
If you have to get metadata of a table like total number of column, column name,
column type etc. , ResultSetMetaData interface is useful because it provides
methods to get metadata from the ResultSet object.
1. import java.sql.*;
2. class Rsmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. PreparedStatement ps=con.prepareStatement("select * from emp");
10.ResultSet rs=ps.executeQuery();
11.ResultSetMetaData rsmd=rs.getMetaData();
12.
13.System.out.println("Total columns: "+rsmd.getColumnCount());
14.System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
15.
1. import java.sql.*;
2. class Dbmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. DatabaseMetaData dbmd=con.getMetaData();
10.
11.System.out.println("Driver Name: "+dbmd.getDriverName());
12.System.out.println("Driver Version: "+dbmd.getDriverVersion());
13.System.out.println("UserName: "+dbmd.getUserName());
14.
1. import java.sql.*;
2. class Dbmd2{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10.DatabaseMetaData dbmd=con.getMetaData();
11.String table[]={"TABLE"};
12.ResultSet rs=dbmd.getTables(null,null,null,table);
13.
14.while(rs.next()){
15.System.out.println(rs.getString(3));
16.}
17.
18.con.close();
19.
20.}catch(Exception e){ System.out.println(e);}
21.
22.}
23.}
download this example
1. import java.sql.*;
2. class Dbmd3{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10.DatabaseMetaData dbmd=con.getMetaData();
11.String table[]={"VIEW"};
12.ResultSet rs=dbmd.getTables(null,null,null,table);
13.
14.while(rs.next()){
15.System.out.println(rs.getString(3));
16.}
17.
18.con.close();
19.
20.}catch(Exception e){ System.out.println(e);}
21.
22.}
23.}