JDBC: Connection With MySQL Database

For connecting with the MySQL database from JAVA application, you need to follow 5 steps to perform database connectivity. Below are connection information specific to MySQL database:

  1. Driver class: The driver class for the MySQL database is com.mysql.jdbc.Driver.
  2. Connection URL: The connection URL for the MySQL database is jdbc:mysql://localhost:3306/FacingIssuesOnITDB where jdbc is the API, MySQL is the database, localhost is the server name on which MySQL is running, we may also use IP address, 3306 is the port number and FacingIssuesOnITDB is the database name. We may use any database, in such case, you need to replace the FacingIssuesOnITDB with your database name.
  3. Username: 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 root as the password.
import java.sql.*;
class MySQLConnection{
public static void main(String args[]){
try{
//Step 1: Register the driver class
 Class.forName("com.mysql.jdbc.Driver");
//Step 2: Create connection with database
   Connection con=DriverManager.getConnection(
   "jdbc:mysql://localhost:3306/FacingIssuesOnITDB","root","root");
//here FacingIssuesOnITDB is database name, root is username and password
//Step 3: Create statement
 Statement stmt=con.createStatement();
//Step 4: Execute query
 ResultSet rs=stmt.executeQuery("select * from emp");   

while(rs.next()){
  System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
}
//Step 5: close connection
con.close();
    }
catch(ClassNotFoundException e){
System.out.println(e);
}
catch(SQLException e){
 System.out.println(e);
    }
}

Here you learn about steps to connect database with application and specific configuration information for MySQL.

See also :

More on JDBC

Follow below links to know more on JDBC and solving JDBC issues :

JDBC Tutorial

JDBC Sample Code

JDBC Issues and Solutions

JDBC Interview Questions And Answers