Pritam Chatterjee
Pritam Chatterjee
Pritam Chatterjee
- Pritam Chatterjee
JDBC
• Java JDBC is a java API to connect and execute query
with the database. JDBC API uses jdbc drivers to connect
with the database.
• Steps:
1. Register the driver class
2. Creating connection
3. Creating statement
4. Executing queries
5. Catching exceptions and Closing connection
Database
• Database name: Testing
• Table: Student
• Fields: Name & ID
Step1 and Step 2
To catch exceptions the steps will be in try
block
1. Register the Driver class
• The forName() method of Class class is used to register the
driver class.
• Class.forName("com.microsoft.sqlserver.jdbc.SQLServerD
river");
• For MySQL: com.mysql.cj.jdbc.Driver
• Connection con=DriverManager.getConnection(
• "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Step 3 and Step 4
Once a connection is obtained we can interact with the database
using Statement Interfaces.
The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the
methods and properties that enable you to send SQL commands and
retrieve data from the database.
Statement: general-purpose access to database, static SQL
statements without parameters.
PreparedStatement: accept input parameters at runtime
CallableStatement: access the database stored procedures,
parameterized stored procedure
Step 3 and Step 4
3. Create Statements
String query = "insert into Students(Name,ID)
values(?,?)";
prSt = con.prepareStatement(query);
prSt.setString(1, "Andrew");
prSt.setString(2, "800");
4. Execute Queries
int count = prSt.executeUpdate();
Step 3 and Step 4
The execute() method: This method is used to execute SQL
DDL statements, it returns a boolean value specifying
weather the ResultSet object can be retrieved.
executeUpdate(): This method is used to execute
statements such as insert, update, delete. It returns an
integer value representing the number of rows affected.
executeQuery(): This method is used to execute statements
that returns tabular data (example select). It returns an
object of the class ResultSet.
Step 5
• Catching Exceptions
catch (ClassNotFoundException e) {
e.printStackTrace(); //
}
catch (SQLException e) {
e.printStackTrace();
}
• Closing Connection
finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
} }