What is the MySQL JDBC driver connection string?
Asked Answered
P

14

130

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.

Parsec answered 22/9, 2009 at 1:33 Comment(2)
To start, the Class.forName() doesn't expect a JDBC connection string, but the JDBC driver class name.Ben
Class.forName() has been obsolete since 2006. Remove it.Yogini
P
120

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");
Paulapauldron answered 22/9, 2009 at 1:39 Comment(2)
how do you find the jdbc path if it's not in environment variables?Philologian
In the sample code the JDBC url has been hardcoded, not searched in any environment variableMaser
T
70

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).

Talkington answered 22/9, 2009 at 1:40 Comment(2)
The links above don't work. Here's a new working link: dev.mysql.com/doc/connector-j/en/…Adar
If I have three properties to use in the connection string, how would the connection string look like - eg: useOldAliasMetadataBehavior=true, useUnicode=true, characterEncoding=UTF-8Henrion
B
20
"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.

Bleak answered 8/7, 2014 at 9:21 Comment(3)
If I have three properties to use in the connection string, how would the connection string look like - eg: useOldAliasMetadataBehavior=true, useUnicode=true, characterEncoding=UTF-8Henrion
@B Pavan Kumar It's a URI, so properties should be separated by ampersands ("&"), as indicated in the specification I quoted.Talkington
@N00bPr0grammer jdbc:mysql://[host][:port]/[database]?useOldAliasMetadataBehavior=true&useUnicode=true&characterEncoding=UTF-8Otherworldly
S
9

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.
Scrim answered 6/11, 2014 at 19:59 Comment(0)
T
4

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);
   }
}
Tevis answered 12/4, 2018 at 9:23 Comment(1)
That's a class name, not a 'connection string'. It has nothing to do with connections whatsoever.Yogini
H
3

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.

Haggi answered 21/8, 2018 at 18:15 Comment(0)
G
3

update for mySQL 8 :

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

Gluck answered 11/3, 2019 at 9:10 Comment(0)
T
2

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();
    }
}
Taenia answered 24/12, 2020 at 21:43 Comment(0)
I
1

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();
        }

    }


}
Intensity answered 11/9, 2020 at 1:6 Comment(0)
M
1

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;
    }
}
Madaras answered 21/11, 2020 at 5:22 Comment(0)
V
0
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]...]
Vashtee answered 8/12, 2017 at 8:35 Comment(0)
R
0

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

Ringsmuth answered 9/5, 2018 at 7:1 Comment(0)
S
0

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

Salesman answered 10/10, 2019 at 16:24 Comment(0)
B
-1

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

Byrle answered 15/12, 2020 at 11:16 Comment(1)
What error? OP didn't mention any error.Yogini

© 2022 - 2024 — McMap. All rights reserved.