How to make a MySQL Connection in JAVA? What is the port number to set on locahost?


You need to use port number 3306 in the URL. The syntax is as follows −

jdbc:mysql://localhost:3306

Example

import java.sql.Connection;
import java.sql.DriverManager;
public class MySQLConnectionToJava {
   public static void main(String[] args) {
      String JDBCURL="jdbc:mysql://localhost:3306/sample?useSSL=false";
      Connection con=null;
      try {
         con = DriverManager.getConnection(JDBCURL,"root","123456");
         if(con!=null) {
            System.out.println("MySQL connection is successful with port 3306.");  
         }
      }
      catch(Exception e) {
         e.printStackTrace();
      } 
   }
}

Output

MySQL connection is successful with port 3306.

Updated on: 16-Dec-2019

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements