Computer >> Computer tutorials >  >> Programming >> MySQL

Connecting to a MySQL database with Java


Use below URL to connect MySQL database. The syntax is as follows −

String MySQLURL="jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false";
String databseUserName="yourUserName";
String databasePassword="yourPassword";

Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class ConnectToDatabase {
   public static void main(String[] args) {
      String MySQLURL = "jdbc:mysql://localhost:3306/web?useSSL=false";
      String databseUserName = "root";
      String databasePassword = "123456";
      Connection con = null;
      try {
         con = DriverManager.getConnection(MySQLURL, databseUserName, databasePassword);
         if (con != null) {
            System.out.println("Database connection is successful !!!!");
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

Database connection is successful !!!!

Here is the snapshot of the output −

Connecting to a MySQL database with Java