How to connect Database using JDBC?

Connect to the database.
    • We can use JDBC API to handle database using Java program and can perform the following activities:
  • 1. Register the Driver class
    • The forName() method of Class is used to register the Driver class.
    • This method is used to dynamically load the Driver class.
      • Syntax:
public static void forName(String className)throws ClassNotFoundException
      • Example:
//register code for Oracle database
Class.forName("oracle.jdbc.driver.OracleDriver");
//register code for MySQL database
Class.forName("com.mysql.jdbc.Driver");

Note: Since JDBC 4.0, no need to registering the driver.

  • 2. Create connection
    • The getConnection() method of DriverManager class is used to establish a 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:
//mysql connection
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//oracle connection
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");
  • 3. Create statement
    • The createStatement() method of Connection interface is used to create a statement. The object of the statement is responsible to execute queries with the database.
      • Syntax:
public Statement createStatement()throws SQLException
      • Example:
Statement stmt=con.createStatement();

  • 4. Execute queries
    • 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.
      • Syntax:
public ResultSet executeQuery(String sql)throws SQLException
      • Example:
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

  • 5. Close connection
    • By closing the connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.
      • Syntax:
public void close()throws SQLException
      • Example:
con.close();

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form