[mysql] What is the MySQL JDBC driver connection string?

I am new to JDBC and I am trying to make a connection to a MySQL database. I am using Connector/J driver, but I cant find the JDBC connection string for my Class.forName() method.

This question is related to mysql jdbc connection-string

The answer is


Here's the documentation:

https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html

A basic connection string looks like:

jdbc:mysql://localhost:3306/dbname

The class.forName string is "com.mysql.jdbc.Driver", which you can find (edit: now on the same page).


Assuming your driver is in path,

String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, "username", "password");

"jdbc:mysql://localhost"

From the oracle docs..

jdbc:mysql://[host][,failoverhost...]
[:port]/[database]
[?propertyName1][=propertyValue1]
[&propertyName2][=propertyValue2]

host:port is the host name and port number of the computer hosting your database. If not specified, the default values of host and port are 127.0.0.1 and 3306, respectively.

database is the name of the database to connect to. If not specified, a connection is made with no default database.

failover is the name of a standby database (MySQL Connector/J supports failover).

propertyName=propertyValue represents an optional, ampersand-separated list of properties. These attributes enable you to instruct MySQL Connector/J to perform various tasks.


protocol//[hosts][/database][?properties]

If you don't have any properties ignore it then it will be like

jdbc:mysql://127.0.0.1:3306/test

jdbc:mysql is the protocol 127.0.0.1: is the host and 3306 is the port number test is the database


update for mySQL 8 :

String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";


It is very simple :

  1. Go to MySQL workbench and lookup for Database > Manage Connections
  2. you will see a list of connections. Click on the connection you wish to connect to.
  3. You will see a tabs around connection, remote management, system profile. Click on connection tab.
  4. your url is jdbc:mysql://<hostname>:<port>/<dbname>?prop1 etc. where <hostname> and <port> are given in the connection tab.It will mostly be localhost : 3306. <dbname> will be found under System Profile tab in Windows Service Name. Default will mostly be MySQL5<x> where x is the version number eg. 56 for MySQL5.6 and 55 for MySQL5.5 etc.You can specify ur own Windows Service name to connect too.
  5. Construct the url accordingly and set the url to connect.

update for mySQL 8 :

String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";

Check whether your Jdbc configurations and URL correct or wrong using the following code snippet.

import java.sql.Connection;
import java.sql.DriverManager;

public class TestJdbc {

    public static void main(String[] args) {

        //db name:testdb_version001
        //useSSL=false (get rid of MySQL SSL warnings)

        String jdbcUrl = "jdbc:mysql://localhost:3306/testdb_version001?useSSL=false";
        String username="testdb";
        String password ="testdb";

        try{

            System.out.println("Connecting to database :" +jdbcUrl);
            Connection myConn =
                    DriverManager.getConnection(jdbcUrl,username,password);

            System.out.println("Connection Successful...!");


        }catch (Exception e){
            e.printStackTrace();
            //e.printStackTrace();
        }

    }


}

Here is a little code from my side :)

needed driver:

com.mysql.jdbc.Driver

download: here (Platform Independent)

connection string in one line:

jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false

example code:

public static void testDB(){
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    try {
        Connection connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/db-name?user=user_name&password=db_password&useSSL=false");
        if (connection != null) {
            Statement statement = connection.createStatement();
            if (statement != null) {
                ResultSet resultSet = statement.executeQuery("select * from test");
                if (resultSet != null) {
                    ResultSetMetaData meta = resultSet.getMetaData();
                    int length = meta.getColumnCount();
                    while(resultSet.next())
                    {
                        for(int i = 1; i <= length; i++){
                            System.out.println(meta.getColumnName(i) + ": " + resultSet.getString(meta.getColumnName(i)));
                        }
                    }
                    resultSet.close();
                }
                statement.close();
            }
            connection.close();
        }
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
}

As the answer seems already been answered, there is not much to add but I would like to add one thing to the existing answers. This was the way of loading class for JDBC driver for mysql

com.mysql.jdbc.Driver

But this is deprecated now. The new driver class is now

com.mysql.cj.jdbc.Driver

Also the driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.


The method Class.forName() is used to register the JDBC driver. A connection string is used to retrieve the connection to the database.

The way to retrieve the connection to the database is shown below. Ideally since you do not want to create multiple connections to the database, limit the connections to one and re-use the same connection. Therefore use the singleton pattern here when handling connections to the database.

Shown Below shows a connection string with the retrieval of the connection:

public class Database {
   
    private String URL = "jdbc:mysql://localhost:3306/your_db_name"; //database url
    private String username = ""; //database username
    private String password = ""; //database password
    private static Database theDatabase = new Database(); 
    private Connection theConnection;
    
    private Database(){
        try{
              Class.forName("com.mysql.jdbc.Driver"); //setting classname of JDBC Driver
              this.theConnection = DriverManager.getConnection(URL, username, password);
        } catch(Exception ex){
            System.out.println("Error Connecting to Database: "+ex);
        }
    }

    public static Database getDatabaseInstance(){
        return theDatabase;
    }
    
    public Connection getTheConnectionObject(){
        return theConnection;
    }
}

For Mysql, the jdbc Driver connection string is com.mysql.jdbc.Driver. Use the following code to get connected:-

class DBConnection {
   private static Connection con = null;
   private static String USERNAME = "your_mysql_username";
   private static String PASSWORD = "your_mysql_password";
   private static String DRIVER = "com.mysql.jdbc.Driver";
   private static String URL = "jdbc:mysql://localhost:3306/database_name";

   public static Connection getDatabaseConnection(){
       Class.forName(DRIVER);
       return con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
   }
}

Check if the Driver Connector jar matches the SQL version.

I was also getting the same error as I was using the

mySQl-connector-java-5.1.30.jar

with MySql 8


it's depends on what service you're using.

if you use MySQL Workbench it wold be some thing like this :

jdbc:mysql://"host":"port number"/

String url = "jdbc:mysql://localhost:3306/";

And of course it will be different if you using SSL/SSH.

For more information follow the official link of Jetbriens (intelliJ idea) :

Connecting to a database #

https://www.jetbrains.com/help/idea/connecting-to-a-database.html


Configuring database connections #

https://www.jetbrains.com/help/idea/configuring-database-connections.html


String url = "jdbc:mysql://localhost:3306/dbname";
String user = "user";
String pass = "pass";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, user, pass);

3306 is the default port for mysql.

If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver").newInstance (); statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.

The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] ยป
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to jdbc

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' Hibernate Error executing DDL via JDBC Statement Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] MySQL JDBC Driver 5.1.33 - Time Zone Issue Spring-Boot: How do I set JDBC pool properties like maximum number of connections? Where can I download mysql jdbc jar from? Print the data in ResultSet along with column names How to set up datasource with Spring for HikariCP? java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why? java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

Examples related to connection-string

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App How to read connection string in .NET Core? Connect to SQL Server Database from PowerShell System.Data.SqlClient.SqlException: Login failed for user Entity Framework change connection at runtime A network-related or instance-specific error occurred while establishing a connection to SQL Server How can I set an SQL Server connection string? VB.NET Connection string (Web.Config, App.Config) Connection string using Windows Authentication How to find SQL Server running port?