java tutorial - How to connect the mysql database in java - java programming - learn java - java basics - java for beginners



  • To connect java application with mysql database.
    • Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
    • Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we can also use IP address, 3306 is a port number and sonoo is a database name. We can use every database, in such case you need to replace sonoo with your database name.
    • Username: The default username for the mysql database is root.
    • Password: It is given by the user at the time of installing mysql database. In this example, we are going to use root as the password.

Create a table in mysql database

create database wikitechy;  
use wikitechy;  
create table wikitechy_employee(id int(10),name varchar(40),age int(3));  
click below button to copy the code. By - java tutorial - team

Sample Code

  • In this example, wikitechy is the database name; root is the username and password.
import java.sql.*;  
class MysqlCon{  
public static void main(String args[]){  
try{  
Class.forName("com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection(  
"jdbc:mysql://localhost:3306/wikitechy","root","root");  
//here wikitechy is database name, root is username and password  
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery("select * from emp");  
while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
con.close();  
}catch(Exception e){ System.out.println(e);}  
}  
}  
click below button to copy the code. By - java tutorial - team
  • To connect java application with the mysql database mysqlconnector.jar file is required to be loaded.

How to load the jar file:

  • There are two ways load the jar file
    • Paste the mysqlconnector.jar file in jre/lib/ext folder
    • Set classpath

Paste the mysqlconnector.jar file in JRE/lib/ext folder:

  • Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.

set classpath:

  • There are two ways to set the classpath:
    • Temporary
    • Permanent

How to set the temporary classpath

  • To open command prompt and write the below command,
C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;  
click below button to copy the code. By - java tutorial - team

How to set the permanent classpath

  • For setting permanent classpath, Go to environment variable and then click on new tab. In variable name write classpath then in variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as C:\folder\mysql-connector-java-5.0.8-bin.jar;.;

Related Searches to How to connect the mysql database in java