English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JDBC Query Database

This chapter provides examples of how to use JDBC applications to select databases. Before executing the following examples, make sure you have the following conditions:

  • To execute the following example, you need to replaceUsernameAndPasswordReplace with actual username and password.

  • Your MySQL or any database you are using has been started and is running.

Necessary steps

To create a new database using a JDBC application, you need to perform the following steps-

  • Import package:It requires you to include the package that contains the JDBC classes required for database programming. Usually, useimport java.sql.*That's enough.

  • Register JDBC driver: It requires you to initialize the driver so that you can open a communication channel with the database.

  • Establish connection:A Connection object representing a physical connection to the selected database must be created using the DriverManager.getConnection () method. When preparing the database URL, choose the database. The following example will connect to the STUDENTS database.

  • Clean up the environment: All database resources must be explicitly closed, rather than relying on JVM garbage collection.

Example code

Copy and paste the following example into JDBCExample.java, as follows compile and run:

//Steps1.Import the required software packages
import java.sql.*;
public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";
   
   public static void main(String[] args) {
   Connection conn = null;
   try{
      //Steps2Register the JDBC driver program
      Class.forName("com.mysql.jdbc.Driver");
      //Steps3: Establish connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");
   }catch(SQLException se){
      //Handle JDBC error
      se.printStackTrace();
   }
      //Handle Class.forName error
      e.printStackTrace();
   }finally{
      //Used to close resources
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }//End try
   System.out.println("Goodbye!");
}//End main
}//End JDBCExample

Now, let's compile the above example as follows:

C:\>javac JDBCExample.java
C:\>

RuntimeJDBCExampleIt will produce the following results-

C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Goodbye!
C:\>