How to connect to a database with JDBC
- Details
- Written by Nam Ha Minh
- Last Updated on 04 June 2019   |   Print Email
In this JDBC tutorial, you will learn how to write Java code to establish connection to a relational database.
In order to make a connection to a specific database system, it requires doing the following 2 steps:
- Load appropriate JDBC driver class using Class.forName()statement.
- Establish a connection using DriverManager.getConnection() statement.
From Java 6 with JDBC 4.0, the first step is no longer needed, as the driver manager attempts to load a suitable JDBC driver from classpath. That means, if you placed a JAR file of JDBC driver for MySQL such as mysql-connector-java-5.1.7-bin.jar in the classpath, the driver manager will automatically load the com.mysql.jdbc.Driverclass which it found in the JAR file.
The DriverManager class is available from package java.sql. There are three versions of getConnection() method which allow us to establish a connection to a database in three different ways:
- static Connection getConnection(String url) :
Establishes a connection from the given database URL in the form of: jdbc:
subprotocol:
subname
- static Connection getConnection(String url, Properties info):
Establishes a connection from the given database URL and a Properties object which includes additional information such as user and password.
- static Connection getConnection(String url, String user, String password):
Establishes a connection from the given database URL, user and password.
As you notice, all methods require a database URL which is a string in a special format that contains information about the database to connect to, such as server name, database name, user, password… Database URL is specific to a particular database system. Following is an example of a database URL for MySQL:
jdbc:mysql://localhost:3306/test
where localhost is server name, 3306 is port number, and test is database name.
All the methods return a Connection object which is used for making SQL queries to the connected database.
The following code examples illustrate establishing connection to a MySQL database. Follow this tutorial to download JDBC driver for MySQL.
1. Java Connect to Database Example with JDBC 3.0 or older
It requires to load the JDBC driver explicitly using Class.forName() method:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectJDBC3 { public static void main(String[] args) { String databaseURL = "jdbc:mysql://localhost:3306/test"; String user = "user"; String password = "password"; Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(databaseURL, user, password); if (conn != null) { System.out.println("Connected to the database"); } } catch (ClassNotFoundException ex) { System.out.println("Could not find database driver class"); ex.printStackTrace(); } catch (SQLException ex) { System.out.println("An error occurred. Maybe user/password is invalid"); ex.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } }
2. Java Connect to Database Example with JDBC 4.0 or newer
From JDBC 4.0 (Java 6), we can safely remove the Class.forName() statement. Following are three examples of connection to the same database in three different ways.
Example 1: getConnection(String url)
In this way, we must pass the user and password directly into the database URL:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBConnect1 { public static void main(String[] args) { String databaseURL = "jdbc:mysql://localhost:3306/test?user=root&password=root123"; Connection conn = null; try { conn = DriverManager.getConnection(databaseURL); if (conn != null) { System.out.println("Connected to the database"); } } catch (SQLException ex) { System.out.println("An error occurred. Maybe user/password is invalid"); ex.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } }
Example 2: getConnection(String url, Properties info) :
In this way, we put the user and password in a Properties object:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class DBConnect2 { public static void main(String[] args) { String databaseURL = "jdbc:mysql://localhost:3306/test"; Connection conn = null; try { Properties props = new Properties(); props.put("user", "root"); props.put("password", "root123"); conn = DriverManager.getConnection(databaseURL, props); if (conn != null) { System.out.println("Connected to the database"); } } catch (SQLException ex) { System.out.println("An error occurred. Maybe user/password is invalid"); ex.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } }
Example 3: getConnection(String url, String user, String password)
In this way, we supply the user and password directly into the method’s arguments:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBConnect3 { public static void main(String[] args) { String databaseURL = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "root123"; Connection conn = null; try { conn = DriverManager.getConnection(databaseURL, user, password); if (conn != null) { System.out.println("Connected to the database"); } } catch (SQLException ex) { System.out.println("An error occurred. Maybe user/password is invalid"); ex.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } }
NOTE: Since Java 1.7, you can use the try-with-resources statement to make connection to database without explicitly closing the connection, for example:
public void connectDatabase(String url, String user, String password) { try (Connection conn = DriverManager.getConnection(url, user, password)) { if (conn != null) { System.out.println("Connected to the database"); } } catch (SQLException ex) { System.out.println("An error occurred. Maybe user/password is invalid"); ex.printStackTrace(); } }
The try-with-resources statement automatically close the resource (database connection) for you.
That's some Java code examples for connecting to a database with JDBC.
JDBC API References:
Connect to a specific database Tutorials:
- Connect to Microsoft SQL Server via JDBC
- Connect to MySQL database via JDBC
- Connect to Oracle database via JDBC
- Connect to PostgreSQL database server via JDBC
- Connect to Apache Derby (Java DB) via JDBC
- Connect to SQLite via JDBC
- Java connecting to MongoDB database examples
Other JDBC Tutorials:
- JDBC's database connection URLs for common databases
- JDBC driver library download
- JDBC CRUD Tutorial
- JDBC Transaction Tutorial
Comments
What is the meaning of this line? please do reply
You have to specify the database name in the database URL connection string.
how it will idetify it has to communicate with which database
3306 is the default port number of MySQL server.