Java Database Connectivity with MySQL

Antosh Dyade November 09, 2022


To connect Java application with the MySQL database, we need to follow 5 following steps.

In this example we are using MySQL as the database. So we need to know following information for the MySQL database:

Driver class: The driver class for the MySQL database is com.mysql.cj.jdbc.Driver.

Connection URL: The connection URL for the MySQL database is jdbc:mysql://localhost:3306/dbname where jdbc is the API, mysql is the database management system, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and dbname is the database name. We may use any database, in such case, we need to replace the dbname with your database name.

Username: The default username for the MySQL database is root.

Password: It is the password given by the user at the time of installing the mysql database. In this example, we are going to use root as the password.

Let's first create a table in the mysql database, 

create database dbname;

use dbname;

create table students(stu_id int,stu_name varchar(100));


Sample Java Code : MyDBExample.java

import java.sql.*;  
class MyDBExample{  
public static void main(String args[]){  
try{  
Class.forName("com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","root","root");  
//here dbname is database name, root is username and password  
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery("select * from students");  
while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2));  
con.close();  
}catch(Exception e){ System.out.println(e);}  
}  
}  


To connect java application with the MySQL database, mysql-connector-j-x.x.xx.jar file is required to be loaded.


Select operating system : Platform Independent  and download zip file and extract in c/d/e.. drive. Here I am demonstrating extraction in c drive. 





Two ways to load the jar file:

  1. Paste the mysqlconnector.jar file in jre/lib/ext folder
  2. Set classpath
1) Paste the mysql-connector-j-x.x.xx.jar file in JRE/lib/ext folder:
Download the mysql-connector-j-x.x.xx.jar file. Go to jre/lib/ext folder and paste the jar file here.


2) Set classpath:
There are two ways to set the CLASSPATH:
  1. Temporary
  2. Permanent
How to set the temporary CLASSPATH
open command prompt and write:  set CLASSPATH=c:\folder\mysql-connector-j-x.x.xx.jar;.;  

How to set the permanent CLASSPATH
Go to environment variable then click on new tab.


In variable name write CLASSPATH and in variable value paste the path to the mysql-connector-j-x.x.xx.jar file by appending ;.; as c:\folder\mysql-connector-j-x.x.xx.jar;.;


Here . indicates the current directory where your class files creates after compilation of java program. 




Share this

Related Posts

Previous
Next Post »