Using JDBC with MySQL – Tutorial and Example

The purpose of this tutorial is to write and test your first JDBC driver programs to connect mysql and manipulate the data stored in MySQL database.

Quick View JDBC MySQL Connector/J.

MySQL provides connectivity for client applications, which allows that the Java program has ability to connect, retrieve and modify data in MySQL through a JDBC driver, the latest official version of MySQL Connector/J is Type 4 pure Java JDBC driver.

Download MySQL JDBC Driver.

Download MySQL JDBC driver from here –MySQL JDBC Driver Download Here, You can install the Connector/J package using either the binary or source distribution, the source distribution requires that you manually add related libraries to Java classpath.

Code Tutorial and Example to connect Mysql via Java JDBC.

The DriverManager class takes over the management of the establishment of Connections. Import java.sql.DriverManager and create a instance of com.mysql.jdbc.Driver, we used class.forName() to register JDBC calsses .

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

Connection conn = null;
try {
    System.out.println("MySQL JDBC Driver Registered!");

    conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" +
    // Do something with the Connection
} catch (ClassNotFoundException e) {
    //Cannot regsister JDBC MySQL driver
}catch (SQLException ex) {
    // handle any errors
    System.out.println("SQLException: " + ex.getMessage());
    System.out.println("SQLState: " + ex.getSQLState());
    System.out.println("VendorError: " + ex.getErrorCode());

Once a connection is established you have got the management authority to MySQL, you are now able to create Statement and PreparedStatement objects, retrieve metadata of the database.

JDBC MySQL Connection String.

In above Code snippets, we used string jdbc:mysql://localhost/test?user=asjava&password=good to connect Mysql, this is JDBC MySQL connection string, the format is:


please use your Mysql connection info(hostname,port,username and password) to replace the corresponding places.

Оцените статью
Добавить комментарий

Your email address will not be published. Required fields are marked *