UNIT-2-JDBC Programming-AJP-6TH-SEM-SUMMER-2024
UNIT-2-JDBC Programming-AJP-6TH-SEM-SUMMER-2024
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL
Java Application
It is a java applet or a servlet that communicates with a data source.
JDBC API
The JDBC API allows Java programs to execute SQL statements and retrieve results.
Some of the important classes and interfaces defined in JDBC API
Driver Manager
It plays an important role in the JDBC architecture. It uses some database-specific
drivers to effectively connect enterprise applications to databases.
JDBC Driver
To communicate with a data source through JDBC, you need a JDBC driver that
intelligently communicates with the respective data source.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Due to large number of translations, execution speed is decreased.
o Dependent on the ODBC driver.
o The ODBC driver needs to be installed on the client machine.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
o it may be considerably faster than a Type 1 driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
o This driver is platform dependent.
Advantage:
o No client side library is required because of application server that can perform many tasks
o Since the communication between client and the middleware server is database
independent, there is no need for the database vendor library on the client.
o We can switch from one database to other without changing the client-side driver class,
by just changing configurations of middleware server.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier.
o Compared to Type 2 drivers, Type 3 drivers are slow due to increased number of network
calls.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
o Completely implemented in Java to achieve platform independence.
o No native libraries are required to be installed in client machine.
Disadvantage:
o Drivers depend on the Database.
Creating connection
• getConnection() method of DriverManager class is used to establish connection with
the database
• Syntax
• public static Connection getConnection(String url) throws SQLException
• public static Connection getConnection(String url, String name, String password)
throws SQLException
• Example:
Connection c=DriverManager.getConnection(jdbc:mysql://localhost:3306/db”,”root”,””);
Creating statement
• CreateStatement() method of Connection interface is used to create statement
• Object of statement is responsible to execute queries with database
• Syntax:
• public Statement createStatement() throws SQLException
• Example:
Statement st=con.createStatement();
Executing queries
• executeQuery() method of Statement interface is used to execute queries to the db
• executeUpdate() method for insert.update,delete query
Syntax:
• public ResultSet executeQuery(String sql)throws SQLException
Example:
ResultSet rs=st.executeQuery(“select * from stud”);
while(rs.next())
{
System.out.println(rs.getInt(1)+””+rs.getString(2));
}
Closing connection
• Close() method of Connection interface is used to close the connection
• Statement & ResultSet will be closed automatically by closing connection object
• Syntax:
• public void close() throws SQLException
• Example:
con.close()
1. createStatement :
From the connection interface, you can create the object for this interface.
It is generally used for general–purpose access to databases and is useful while using
static SQL statements at runtime.
createStatement() method is used with con object of Connection interface.
Syntax:
Statement statement = connection.createStatement();
Example:
Statement st=con.createStatement();
Once the Statement object is created, there are three ways to execute it.
o Using execute()
o Using executeUpdate()
Executes the query.
It is used for create, drop, insert, update, delete etc.
o Using executeQuery()
Executes the select query.
It returns an instance of ResultSet.
2. PreparedStatement:
It is used when you plan to use the SQL statements multiple times.
The PreparedStatement interface accepts input parameters at runtime.
In this, “?” is used instead of the parameter, if you can pass the parameter dynamically
by using the methods of PREPARED STATEMENT at run time.
Example
// Step: to Create a statement
PreparedStatement ps = con.prepareStatement(
" insert into student values(?,?,?)");
// Step: to Execute the query
ps.setString(1, "1423"); //Enr_no
ps.setString(2, "abc"); //Name
ps.setString(3, "computer"); //Branch
ps.executeUpdate();
Methods of PreparedStatement:
3. CallableStatement:
The Callable Statement interface provided by JDBC API helps in executing stored
procedures.
CallableStatement interface is used to call the stored procedures.
Suppose you need to get the age of student based on the date of birth, you may
create a procedure that receives date as the input and returns age of the student as
the output.
Three types of parameters exist: IN, OUT, and INOUT.
The PreparedStatement object only uses the IN parameter.
The CallableStatement object can use all the three.
Syntax:
CallableStatement cstmt = con.prepareCall("{call Procedure_name(?, ?}");
Example
CallableStatement cs=conn.prepareCall("{call getage(?,?)}");
cs.setString(1,”08-10-1990”);
cs.registerOutParameter(2,Types.VARCHAR);
cs.execute();
System.out.println(cs.getString(2));
cs.close();
The term "result set" refers to the row and column data contained in a ResultSet object.
A ResultSet object maintains a cursor that points to the current row in the result set.
The SELECT statement is the standard way to select rows from a database and view
them in a result set.
The java.sql.ResultSet interface represents the result set of a database query.
The methods of the ResultSet interface divide into three categories
Que:6: List out the types and concurrency of ResultSet interface with
example in JDBC.
Method Description
Concurency of ResultSet:
Method Description
Example:
try {
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex)
{
....
}
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.
Methods of ResultSetMetaData interfaces are shown in table:
Method Description
Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
Example:
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bmu","root","root");
DatabaseMetaData dbmd=con.getMetaData();
System.out.println("getDatabaseProductName:“ +dbmd.getDatabaseProductName());
System.out.println("getDatabaseProductVersion():“ +dbmd.getDatabaseProductVersion());
System.out.println("getDriverName():"+dbmd.getDriverName());
System.out.println("getDriverVersion():“ +dbmd.getDriverVersion());
System.out.println("getURL():"+dbmd.getURL());
System.out.println("getUserName():"+dbmd.getUserName());
Example:
import java.sql.*;
class UpdateDemo{
try{ Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bmu","root","root");
Statement stmt=con.createStatement();
stmt.executeUpdate(query);
stmt.close();
con.close();
Method Description
Example:
import java.sql.*;
class RollbackDemo{
try{ Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bmu","root","root");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
con.close();