JDBC
Java Database Connectivity(JDBC)
Use JDBC�
JDBC API to handle database using Java program and can perform following activities
JDBC Driver�
JDBC Driver is required to process SQL requests and generate result. The following are the different types of driver available in JDBC.
JDBC-ODBC bridge�Type-1 Driver act as a bridge between JDBC and other database connectivity mechanism(ODBC). This driver converts JDBC calls into ODBC calls and redirects the request to the ODBC drive�
Contd..
Advantages:
Disadvantages:
Native API Driver�This type of driver make use of Java Native Interface(JNI) call on database specific native client API. These native client API are usually written in C and C++
Contd..
Advantage
Disadvantage
Network Protocol Driver�This driver translate the JDBC calls into a database server independent and Middleware server-specific calls. Middleware server further translate JDBC calls into database specific calls.
Contd..
Advantage
Disadvantage
Thin Driver�This is Driver called Pure Java Driver because. This driver interact directly with database. It does not require any native database library, that is why it is also known as Thin Driver.�
Contd..
Advantage
Disadvantage
Java Database Connectivity with 5 Steps�
There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
Register the Driver�
Create the connection object�
The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password) throws SQLException
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
Create the Statement object��
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Statement stmt=con.createStatement();
Execute the query�
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.
public ResultSet executeQuery(String sql)throws SQLException
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Close the connection object�
By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.
public void close()throws SQLException
con.close();