My sql Connection with Java

MysqlConnect.java

import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
    System.out.println("MySQL Connect Example.");
    
    try {
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/"; // Connection url for mysql
    String dbName = "test";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "";
    
      Class.forName(driver).newInstance();
      conn = DriverManager.getConnection(url+dbName,userName,password);
      System.out.println("Connected to the database");
      conn.close();
      System.out.println("Disconnected from database");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

Run this program you need
mysql-connector-java-5.1.13-bin.jar

If you connect with oracle than Connection url is : "jdbc:oracle:thin:@localhost:1521:oracle"

"oracle" is a database, "1521" is a database port.

 

Following table lists down popular JDBC driver names and database URL format.

RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName