How To Use JDBC To Connect MySql Database

This article will show you examples of how to use JDBC to connect to a MySQL database server.

1. Download MySQL Server.

  1. If your purpose is just for study, you can download XAMPP for using MySQL DB, XAMPP includes both Apache, MySql, and PHP.
  2. If you want to use the MySQL server separately, you can go to the MySQL download page to download and install the MySQL server.
  3. This tutorial just uses XAMPP. After download and install XAMPP, you can start it by clicking Windows Start —> XAMPP —> XAMPP Control Panel.
  4. In the XAMPP Control Panel, you should start MySQL and Apache Server. When you see the green rectangle in the service Module column, the server startup is ready.
  5. Click the MySQL Admin button in the XAMPP Control panel, there will pop up a web browser open the phpMyAdmin web page. You can manage the MySQL database in this web-based GUI.
  6. Click the MySQL database test in the phpMyAdmin left panel to select it.
  7. Click the New link to create a table student under the database test.
  8. The student table contains 2 columns, one is the name varchar(100) and the other is the email varchar(100).

2. Download MySQL Server JDBC Driver.

  1. Click here go to download the MySQL JDBC driver page.
  2. Click the Archives tab at the top of the download page.
  3. Select the MySQL Connector/J version in the Product Version drop-down list.
  4. Select the Platform Independent option in the Operating System drop-down list.
  5. Then it will list all the MySQL Connector/J download items, click the Download button at the end of each item row to download the MySQL Connector/J JDBC driver file.
  6. Do not need to Sign Up, just click the bottom link ( No thanks, just start my download ) to download the MySQL JDBC jar directly.
  7. After download, unzip it to a local folder and add the jar file to your java project follow the below steps.
  8. Right-click the eclipse java project, click the Properties menu item in the popup menu list.
  9. In the java project properties dialog, click the Java Build Path item on the left side.
  10. Then click the Libraries tab on the right side.
  11. Click the Add External JARs… button to browse and add the MySQL Connector/J JDBC driver jar files into the java project.

3. MySQL JDBC Example Code.

  1. The basic JDBC java code for database connection is the same, the only difference is the database connection url and JDBC driver class name.
    /* Register database jdbc driver class. */			
    Class.forName("com.mysql.jdbc.Driver");
    			
    /* Create database connection url. */
    String mysqlConnUrl = "jdbc:mysql://localhost:3306/test";
    			
    /* db user name. */
    String mysqlUserName = "root";
    			
    /* db password. */
    String mysqlPassword = "";
    			
    /* Get the Connection object. */
    java.sql.Connection conn = DriverManager.getConnection(mysqlConnUrl, mysqlUserName , mysqlPassword);
    
  2. Below is the Complete MySQL JDBC Connection java code. You can see java code comments for detailed explanations. Please note do not forget to close the java.sql.Connection object after use it. If not, the DB connection speed will be slower and slower.
    package com.dev2qa.java.jdbc;
    
    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.DriverManager;
    
    public class MySqlExample {
    
    	public static void main(String[] args) {
    		
    		try
    		{
    			MySqlExample mySqlExample = new MySqlExample();
    			
    			Connection conn = mySqlExample.getMySqlConnection();
    			
    			/* You can use the connection object to do any insert, delete, query or update action to the mysql server.*/
    			
    			/* Do not forget to close the database connection after use, this can release the database connection.*/
    			conn.close();
    		}catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}
    	}
    	
    	/* This method return java.sql.Connection object from MySQL server. */
    	public Connection getMySqlConnection()
    	{
    		/* Declare and initialize a sql Connection variable. */
    		Connection ret = null;
    		
    		try
    		{
    		
    			/* Register for jdbc driver class. */
    			Class.forName("com.mysql.jdbc.Driver");
    			
    			/* Create connection url. */
    			String mysqlConnUrl = "jdbc:mysql://localhost:3306/test";
    			
    			/* db user name. */
    			String mysqlUserName = "root";
    			
    			/* db password. */
    			String mysqlPassword = "";
    			
    			/* Get the Connection object. */
    			ret = DriverManager.getConnection(mysqlConnUrl, mysqlUserName , mysqlPassword);
    			
    			/* Get related meta data for this mysql server to verify db connect successfully.. */
    			DatabaseMetaData dbmd = ret.getMetaData();
    			
    			String dbName = dbmd.getDatabaseProductName();
    			
    			String dbVersion = dbmd.getDatabaseProductVersion();
    			
    			String dbUrl = dbmd.getURL();
    			
    			String userName = dbmd.getUserName();
    			
    			String driverName = dbmd.getDriverName();
    			
    			System.out.println("Database Name is " + dbName);
    			
    			System.out.println("Database Version is " + dbVersion);
    			
    			System.out.println("Database Connection Url is " + dbUrl);
    			
    			System.out.println("Database User Name is " + userName);
    			
    			System.out.println("Database Driver Name is " + driverName);
    						
    		}catch(Exception ex)
    		{
    			ex.printStackTrace();
    		}finally
    		{
    			return ret;
    		}
    	}
    
    }
    
  3. Run the above code, you can see the below output in the java console.
    Database Name is MySQL
    Database Version is 5.5.5-10.1.24-MariaDB
    Database Connection Url is jdbc:mysql://localhost:3306/test
    Database User Name is root@localhost
    Database Driver Name is MySQL Connector Java

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.