.


Divya

How to connect to the mysql database in java JDBC


Connecting Java application with MySql database is very easy just follow the below step to perform database connectivity.

In this example I am using MySql database and fetch the data of students.

For connecting Java application with MySql database 4 things needed :

  1. Driver class
  2. JDBC Connection URL
  3. Username
  4. Password
  5. Jar File

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

2.JDBC Connection URL:  The JDBC connection URL for the mysql database is jdbc:mysql://localhost:3306/db_name

 

Example: jdbc:mysql://localhost:3306/students

  1. Here my database name is students you just put your database name. 
  2. Here JDBC is the API.
  3. Mysql is the database.
  4. Localhost is the server name on which mysql is running.
  5. 3306 is the port number

3.Username: Put your username if any.The default username for the mysql database is root.

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

5.Jar File: Download Here

Example:

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/students","root","Students@123"); 
  //here students is database name, root is username and password  is Students@123 
  Statement stmt=con.createStatement();  
  ResultSet rs=stmt.executeQuery("select * from students_data”); 
   while(rs.next())  
  System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3)); 
   con.close();  
  }
  catch(Exception e){ System.out.println(e);}  
  }  
  }  


.