In this post we will see the sample code to connect to MySQL using JDBC drivers in java.
For connecting to MySQL database we will need the following
1. Connection URL
The format is
jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]]
example:
jdbc:mysql://localhost:3306/mysql
2. User Name
User Name of the database that we need to connect.
3. Password
Password of the database that we need to connect.
4. mysql-connector-java-
5. MySql JDBC Driver Name
The driver used is com.mysql.jdbc.Driver
Steps: Connect to MySQL using JDBC
1. Register the JDBC Driver
Using the
Class.forName(...) we can register the MYSql JDBC driver.
2. Create Connection using DriveManager
Using the
DriverManager.getConnection(url,user,password) we can create the connection to the database.
Please remember to add the mysql-connector-java-
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.kscodes.sampleproject.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class MySqlConnectExample { public static String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver"; public static String CONNECTION_URL = "jdbc:mysql://localhost:3306/mysql"; public static String CONNECTION_USER = "kscodes"; public static String CONNECTION_PASSWORD = "kscodes"; public static void main(String[] args) { System.out.println("1. Register the JDBC Driver"); try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { System.out.println("Error while registering JDBC driver"); System.exit(0); } System.out.println("MySQL JDBC Driver Registered Successfully"); System.out.println("2. Create Connection using DriveManager"); Connection connection = null; try { connection = DriverManager.getConnection(CONNECTION_URL, CONNECTION_USER, CONNECTION_PASSWORD); } catch (SQLException e) { System.out.println("Failed to create Connection"); System.exit(0); } System.out.println("Connection created Successfully. Now use this connection to perform database operations....."); // Use this connection to fire queries and perform other database operations } } |
Output
1 2 3 4 |
1. Register the JDBC Driver MySQL JDBC Driver Registered Successfully 2. Create Connection using DriveManager Connection created Successfully. Now use this connection to perform database operations..... |
Exceptions to be caught
1. ClassNotFoundException
2. SQLException