Connect to MySQL using JDBC

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]]

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--bin.jar in our classpath. (we are using mysql-connector-java-5.1.38-bin.jar) You can get this jar from MySql Connector J

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--bin.jar in the class path before running the code.



Exceptions to be caught

1. ClassNotFoundException
2. SQLException