Java JDBC Tutorial: What Is API
Java JDBC Tutorial: What Is API
Java JDBC Tutorial: What Is API
Java JDBC is a java API to connect and execute query with the database. JDBC API uses
jdbc drivers to connect with the database.
What is API
API (Application programming interface) is a document that contains description of all the
features of a product or software. It represents classes and interfaces that software
programs can follow to communicate with each other. An API can be created for
applications, libraries, operating systems, etc
JDBC Driver
JDBC Driver is a software component that enables java application to interact with
the database.There are 4 types of JDBC drivers:
Advantages:
o easy to use.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
Disadvantage:
o Drivers depends on the Database.
Steps to connect to the database in java
There are 5 steps to connect any java application with the database in java using JDBC.
They are as follows:
o Creating connection
o Creating statement
o Executing queries
o Closing connection
4. Password: Password is given by the user at the time of installing the oracle
database.
1.
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}
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.
3) public boolean execute(String sql): is used to execute queries that may return
multiple results.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr")
;
Statement stmt=con.createStatement();
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:
2) public boolean previous(): is used to move the cursor to the one row previous
position.
3) public boolean first(): is used to move the cursor to the first row in result set ob
4) public boolean last(): is used to move the cursor to the last row in result set ob
5) public boolean absolute(int row): is used to move the cursor to the specified row numbe
object.
6) public boolean relative(int row): is used to move the cursor to the relative row numbe
object, it may be positive or negative.
7) public int getInt(int columnIndex): is used to return the data of specified column index of
int.
8) public int getInt(String is used to return the data of specified column name of
columnName): int.
9) public String getString(int is used to return the data of specified column index of
columnIndex): String.
10) public String getString(String is used to return the data of specified column name of
columnName): String.
Example of Scrollable ResultSet
Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr")
;
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_
UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
con.close();
}}
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter inde
public void setString(int paramIndex, String sets the String value to the given parameter index
value)
public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.
public void setDouble(int paramIndex, double sets the double value to the given parameter inde
value)
public int executeUpdate() executes the query. It is used for create, dro
delete etc.
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:@localhost:1521:xe","hr","hr")
;
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
}
Example of PreparedStatement interface that updates the record
1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");
2. stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name
3. stmt.setInt(2,101);
4.
5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");
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.
public String getColumnName(int index)throws SQLException it returns the column name of the
index.
public String getColumnTypeName(int index)throws it returns the column type name for th
SQLException
public String getTableName(int index)throws SQLException it returns the table name for the speci
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.
must not have the return type. must have the return type.
We can call functions from the procedure. Procedure cannot be called from function
Procedure supports input and output parameters. Function supports only input parameter.
Exception handling using try/catch block can be used in Exception handling using try/catch can
stored procedures. defined functions.
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.
1. import java.sql.*;
2. public class Proc {
3. public static void main(String[] args) throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
10. stmt.setInt(1,1011);
11. stmt.setString(2,"Amit");
12. stmt.execute();
13.
14. System.out.println("success");
15. }
16. }
Now check the table in the database, value is inserted in the user420 table.
The Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE,
BLOB, CLOB etc.
1. import java.sql.*;
2.
3. public class FuncSum {
4. public static void main(String[] args) throws Exception{
5.
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. CallableStatement stmt=con.prepareCall("{?= call sum4(?,?)}");
11. stmt.setInt(2,10);
12. stmt.setInt(3,43);
13. stmt.registerOutParameter(1,Types.INTEGER);
14. stmt.execute();
15.
16. System.out.println(stmt.getInt(1));
17.
18. }
19. }
The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
Consistency ensures bringing the database from one consistent state to another consistent
state.
Durability means once a transaction has been committed, it will remain so, even in the
event of errors, power loss etc.
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
1. import java.sql.*;
2. class FetchRecords{
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","syst
em","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
10. stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
11.
12. con.commit();
13. con.close();
14. }}
If you see the table emp400, you will see that 2 records has been added.
1. import java.sql.*;
2. import java.io.*;
3. class TM{
4. public static void main(String args[]){
5. try{
6.
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syst
em","oracle");
9. con.setAutoCommit(false);
10.
11. PreparedStatement ps=con.prepareStatement("insert into user420 values(?,?,?)");
12.
13. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
14. while(true){
15.
16. System.out.println("enter id");
17. String s1=br.readLine();
18. int id=Integer.parseInt(s1);
19.
20. System.out.println("enter name");
21. String name=br.readLine();
22.
23. System.out.println("enter salary");
24. String s3=br.readLine();
25. int salary=Integer.parseInt(s3);
26.
27. ps.setInt(1,id);
28. ps.setString(2,name);
29. ps.setInt(3,salary);
30. ps.executeUpdate();
31.
32. System.out.println("commit/rollback");
33. String answer=br.readLine();
34. if(answer.equals("commit")){
35. con.commit();
36. }
37. if(answer.equals("rollback")){
38. con.rollback();
39. }
40.
41.
42. System.out.println("Want to add more records y/n");
43. String ans=br.readLine();
44. if(ans.equals("n")){
45. break;
46. }
47.
48. }
49. con.commit();
50. System.out.println("record successfully saved");
51.
52. con.close();//before closing connection commit() is called
53. }catch(Exception e){System.out.println(e);}
54.
55. }}
It will ask to add more records until you press n. If you press n, transaction is committed.
Batch Processing in JDBC
Instead of executing a single query, we can execute a batch (group) of queries. It makes
the performance fast.
Fast Performance
Method Description
o Create Connection
o Create Statement
o Execute Batch
o Close Connection
1. import java.sql.*;
2. class FetchRecords{
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","syst
em","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.addBatch("insert into user420 values(190,'abhi',40000)");
10. stmt.addBatch("insert into user420 values(191,'umesh',50000)");
11.
12. stmt.executeBatch();//executing the batch
13.
14. con.commit();
15. con.close();
16. }}
If you see the table user420, two records has been added.
It will add the queries into the batch until user press n. Finally it executes the batch. Thus
all the added queries will be fired.
Assertion:
Assertion is a statement in java. It can be used to test your assumptions about the
program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.
Advantage of Assertion:
It provides an effective way to detect and correct programming errors.
1. assert expression;
2. Do not use assertion, if you don't want any error in any situation.
Advantage of Varargs:
We don't have to provide overloaded methods so less code.
Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows:
Output:number is 500
hello
number is 1000
my
name
is
varargs
Output:Hello
Java
Output:50 5
download this example
1.
2. class UnboxingExample1{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5. int a=i;
6.
7. System.out.println(a);
8. }
9. }
10.
Test it Now
Output:50
1.
2. class UnboxingExample2{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5.
6. if(i<100){ //unboxing internally
7. System.out.println(i);
8. }
9. }
10. }