JavaJDBC 2
JavaJDBC 2
Steps
• There are 5 steps to connect any java
application with the database using JDBC.
• These steps are as follows:
– Register the Driver class
– Create connection
– Create statement
– Execute queries
– Close connection
1) Register the driver class
• The forName() method of Class class is used
to register the driver class. This method is
used to dynamically load the driver
class.Syntax of forName() method
– public static void forName(String className)throws Class
NotFoundException
• Here, Java program is loading oracle driver to
esteblish database connection.
– Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
• The getConnection() method of DriverManager class is
used to establish connection with the database.
• Syntax of getConnection() method :-
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) 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. Syntax of close()
method :-
public void close()throws SQLException
Example to close connection :-
con.close();
Java Database Connectivity with MySQL
• To connect Java application with the MySQL database, we need to
follow 5 following steps.
• In this example we are using MySql as the database. So we need to
know following informations for the mysql database:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:
1521:xe","system","oracle");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Res
ultSet.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.
• Let's see the example of parameterized query:
• 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.
Methods :-
• public void setInt(int paramIndex, int value)
– sets the integer value to the given parameter index.
• public void setString(int paramIndex, String value)
– sets the String value to the given parameter index.
• public void setFloat(int paramIndex, float value)
– sets the float value to the given parameter index.
• public void setDouble(int paramIndex, double value)
– sets the double value to the given parameter index.
• public int executeUpdate()
– executes the query. It is used for create, drop, insert,
update, delete etc.
• public ResultSet executeQuery()
– executes the select query. It returns an instance of
ResultSet.