by BehindJava

What are the steps to connect to a database using JDBC API

Home » java » What are the steps to connect to a database using JDBC API

In this tutorial we are going to learn in detail about in establishing a connection to a database using JDBC API.

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

Sample Code Snippet:

public void GetKey() throws Exception {        
        String cipher="AES";
        //step1 load the driver class  
		Class.forName("com.mysql.jdbc.Driver");          //step2 create  the connection object  
		Connection con=DriverManager.getConnection(  		"jdbc:mysql://localhost:3306/AES","root","root123");
		String sqlSelectQuery = "select key from Global where Algorithm=?";
        //step3 create statement
		PreparedStatement pstmt = con.prepareStatement(sqlSelectQuery);		pstmt.setString(1, cipher);
        //step4 execute queries
		 ResultSet rs = pstmt.executeQuery();        //step5 Close connection
		rs.close();    		rs.close();
		con.close();
}