Lecture Topic 2.3.1
Lecture Topic 2.3.1
Java application calls the JDBC library. JDBC loads a driver which talks to the database.
The user application invokes JDBC methods to send SQL statements to the database and retrieves results. JDBC driver manager is used to
connect Java applications to the correct JDBC driver . JDBC driver test suite is used to ensure that the installed JDBC driver is JDBC Compliant.
•Type 1
• JDBC-ODBC Bridge
•Type 2
•Type 3
•Type 4
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your database.
The type 1 driver is not considered a deployment-level driver, and is typically used for development and testing purposes only.
There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","password");
Statement stmt=con.createStatement();
The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can
be used to get all the records of a table.
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close
the connection.
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement.
To connect java application with the oracle database, we need to follow 5 following steps.
In this example, we are using Oracle 10g as the database. So we need to know following information for the oracle database:
Connection URL: The connection URL for the oracle10G database is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the
database, thin is the driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and XE
is the Oracle service name. You may get all these information from the tnsnames.ora file.
Password: It is the password given by the user at the time of installing the oracle database.
Create a TableBefore establishing connection, let's first create a table in oracle database. Following is the SQL query to create a table.
1. create table emp(id number(10),name varchar2(40),age number(3));
In this example, we are connecting to an Oracle database and getting data from emp table. Here, system and oracle are the username and
password of the Oracle database.
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7.
8. //step2 create the connection object
9. Connection con=DriverManager.getConnection(
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=con.createStatement();
14.
15. //step4 execute query
16. ResultSet rs=stmt.executeQuery("select * from emp");
17. while(rs.next())
18. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
19.
20. //step5 close the connection object
21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }
The above example will fetch all the records of emp table.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
Link:: https://static.javatpoint.com/src/jdbc/ojdbc14.jar
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
temporary
permanent
Firstly, search the ojdbc14.jar file then open command prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
Go to environment variable then click on new tab. In variable name write classpath and in variable value paste the path to ojdbc14.jar by
appending ojdbc14.jar;.; as C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;
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.
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
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. //int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 where id=33");
10. int result=stmt.executeUpdate("delete from emp765 where id=33");
11. System.out.println(result+" records affected");
12. con.close();
13. }}
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.
Improves performance: The performance of the application will be faster if you use PreparedStatement interface because query is compiled
only once.
The prepareStatement() method of Connection interface is used to return the object of PreparedStatement. Syntax:
1. public PreparedStatement prepareStatement(String query)throws SQLException{}
1. create table emp(id number(10),name varchar2(50));
1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. 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. }
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.
The differences between stored procedures and functions are given below:
The prepareCall() method of Connection interface returns the instance of CallableStatement. Syntax is given below:
1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
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 user12 values(id,name);
7. end;
8. /
create table user12(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
user12. Note that you need to create the user12 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( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
7.
8. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
9. stmt.setInt(1,1011);
10. stmt.setString(2,"Amit");
11. stmt.execute();
12.
13. System.out.println("success");
14. }
15. }
Now check the table in the database, value is inserted in the user12 table.
Reference Links:
https://www.tutorialspoint.com/jdbc/jdbc-statements.htm
https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html
https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html
https://www.javatpoint.com/Statement-interface
https://www.javatpoint.com/PreparedStatement-interface
https://www.javatpoint.com/CallableStatement-interface
Video Link:
https://youtu.be/eEqPrlu28Sc
https://youtu.be/v5vLuCBv8vg