🌐
MySQL
dev.mysql.com › doc › connector-j › en
MySQL :: MySQL Connector/J Developer Guide
This manual describes how to install, configure, and develop database applications using MySQL Connector/J 26.7, a JDBC and X DevAPI driver for communicating with MySQL servers.
🌐
w3resource
w3resource.com › mysql › mysql-java-connection.php
MySQL Java Connector - w3resource
February 28, 2026 - For example add the Connector/J driver to your classpath using one of the following forms, depending on your command shell : # Bourne-compatible shell (sh, ksh, bash, zsh): shell> export CLASSPATH=/path/MySQL-connector-java-ver-bin.jar:$CLASSPATH # C shell(csh, tcsh): shell> setenv CLASSPATH /path/MySQL-connector-java-ver-bin.jar:$CLASSPATH
🌐
GitHub
github.com › mysql › mysql-connector-j
GitHub - mysql/mysql-connector-j: MySQL Connector/J · GitHub
MySQL provides connectivity for client applications developed in the Java programming language with MySQL Connector/J, a driver that implements the Java Database Connectivity (JDBC) API and also MySQL X DevAPI.
Author   mysql
🌐
MySQL
dev.mysql.com › doc › connector-j › en › connector-j-usagenotes-connect-drivermanager.html
MySQL :: MySQL Connector/J Developer Guide :: 7.1 Connecting to MySQL Using the JDBC DriverManager Interface
public class LoadDriver { public static void main(String[] args) { try { // The newInstance() call is a work around for some // broken Java implementations Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance(); } catch (Exception ex) { // handle the error } } } After the driver has been registered with the DriverManager, you can obtain a Connection instance that is connected to a particular database by calling DriverManager.getConnection(): Example 7.1 Connector/J: Obtaining a connection from the DriverManager
🌐
Baeldung
baeldung.com › home › persistence › spring persistence › connect java to a mysql database
Connect Java to a MySQL Database | Baeldung
April 24, 2024 - JDBC (Java Database Connectivity) is an API for connecting and executing queries on a database. During the course of this article, we’ll typically use several common JDBC properties: Connection URL – a string that the JDBC driver uses to connect to a database. It can contain information such as where to search for the database, the name of the database to connect to and other configuration properties: jdbc:mysql://[host][,failoverhost...] [:port]/[database] [?propertyName1][=propertyValue1] [&propertyName2][=propertyValue2]...
🌐
MySQL Tutorial
mysqltutorial.org › home › mysql jdbc › connecting to mysql using jdbc driver
Connecting to MySQL Using JDBC Driver
May 9, 2024 - The following defines the Main class that uses the MySQLConnection class to connect to the MySQL database: import java.sql.SQLException; public class Main { public static void main(String[] args){ try (var connection = MySQLConnection.connect()){ ...
🌐
TutorialsPoint
tutorialspoint.com › java_mysql › java_mysql_connections.htm
Java & MySQL - Connections
To make the same connection made by the previous examples, use the following code − · import java.util.*; String URL = "jdbc:mysql://localhost/TUTORIALSPOINT"; Properties info = new Properties( ); info.put( "user", "guest" ); info.put( "password", "guest123" ); Connection conn = DriverManager.getConnection(URL, info);
Find elsewhere
🌐
CodeJava
codejava.net › java-se › jdbc › connect-to-mysql-database-via-jdbc
Java connect to MySQL database with JDBC
March 7, 2020 - Maybe user/password is invalid"); ex.printStackTrace(); } Type the following command to compile the example program: javac MySQLConnectExample.javaSuppose the Connect/J library is placed in the same directory as the MySQLConnectExample.java file. Type the following command to run: java -cp ...
🌐
Vogella
vogella.com › tutorials › MySQLJava › article.html
MySQL and Java JDBC - Tutorial
The MySQL JDBC driver is called MySQL Connector/J. You find the latest MySQL JDBC driver under the following URL: https://dev.mysql.com/downloads/connector/j. The download contains a JAR file which we require later. In this exercise, you create a new database, a new user and an example ...
Top answer
1 of 14
548

Here's a step by step explanation how to install MySQL and JDBC and how to use it:

  1. Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306.

  2. Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).

    If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.

    If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application.

    java -cp .;/path/to/mysql-connector.jar com.example.YourClass

    The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used.

    If you're developing a servlet based WAR application and wish to manually manage connections (poor practice, actually), then you need to ensure that the JAR ends up in /WEB-INF/lib of the build. See also How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib. The better practice is to install the physical JDBC driver JAR file in the server itself and configure the server to create a JDBC connection pool. Here's an example for Tomcat: How should I connect to JDBC database / datasource in a servlet based application?

  3. Create a database in MySQL. Let's create a database javabase. You of course want World Domination, so let's use UTF-8 as well.

     CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
    
  4. Create a user for Java and grant it access. Simply because using root is a bad practice.

     CREATE USER 'java'@'localhost' IDENTIFIED BY 'password';
     GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password';
    

    Yes, java is the username and password is the password here.

  5. Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:

    jdbc:mysql://hostname:port/databasename
    • hostname: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost. It can also be an IP address like 127.0.0.1. If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config.

    • port: The TCP/IP port where MySQL server listens on. This is by default 3306.

    • databasename: The name of the database you'd like to connect to. That's javabase.

    So the final URL should look like:

    jdbc:mysql://localhost:3306/javabase
  6. Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection.

     String url = "jdbc:mysql://localhost:3306/javabase";
     String username = "java";
     String password = "password";
    
     System.out.println("Connecting database ...");
    
     try (Connection connection = DriverManager.getConnection(url, username, password)) {
         System.out.println("Database connected!");
     } catch (SQLException e) {
         throw new IllegalStateException("Cannot connect the database!", e);
     }
    

    If you get a SQLException: No suitable driver, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). See also The infamous java.sql.SQLException: No suitable driver found. Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:

     System.out.println("Loading driver ...");
    
     try {
         Class.forName("com.mysql.cj.jdbc.Driver"); // Use com.mysql.jdbc.Driver if you're not on MySQL 8+ yet.
         System.out.println("Driver loaded!");
     } catch (ClassNotFoundException e) {
         throw new IllegalStateException("Cannot find the driver in the classpath!", e);
     }
    

    Note that the newInstance() call is not needed here. It's in case of MySQL just to fix the old and buggy org.gjt.mm.mysql.Driver. Explanation here. If this line throws ClassNotFoundException, then the JAR file containing the JDBC driver class is simply not been placed in the classpath. Please also note that it's very important to throw an exception so that the code execution is immediately blocked, instead of suppressing it of merely printing the stack trace and then continuing the rest of the code.

    Also note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.

    If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException: Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:

    1. IP address or hostname in JDBC URL is wrong.
    2. Hostname in JDBC URL is not recognized by local DNS server.
    3. Port number is missing or wrong in JDBC URL.
    4. DB server is down.
    5. DB server doesn't accept TCP/IP connections.
    6. DB server has run out of connections.
    7. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.

    To solve the one or the other, follow the following advices:

    1. Verify and test them with ping.
    2. Refresh DNS or use IP address in JDBC URL instead.
    3. Verify it based on my.cnf of MySQL DB.
    4. Start the DB.
    5. Verify if mysqld is started without the --skip-networking option.
    6. Restart the DB and fix your code accordingly that it closes connections in finally.
    7. Disable firewall and/or configure firewall/proxy to allow/forward the port.

    Note that closing the Connection is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection in a try-with-resources statement. This also applies to Statement, PreparedStatement and ResultSet. See also How often should Connection, Statement and ResultSet be closed in JDBC?

That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.


Using a Singleton Pattern and/or a static variable for the DB Connection is a bad practice. See among others Is it safe to use a static java.sql.Connection instance in a multithreaded system? This is a #1 starters mistake. Make sure you don't fall in this trap.

2 of 14
233

DataSource

DriverManager is a fairly old way of doing things. The better way is to get a DataSource object. Either by using JNDI to look one up that your app server container already configured for you:

Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");

… or by instantiating and configuring one from your database driver directly, such as com.mysql.cj.jdbc.MysqlDataSource (see documentation):

MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");

… and then obtain connections from it, same as above:

Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
…
rs.close();
stmt.close();
conn.close();

In modern Java, use try-with-resources syntax to automatically close JDBC resources (now AutoCloseable).

try (
    Connection conn = dataSource.getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
) {
    …
}
🌐
GitHub
github.com › wagnerjfr › sample-java-mysql-connector
GitHub - wagnerjfr/sample-java-mysql-connector: Sample Java applications which show how to use MySQL Server Community (8.0.20) and MySQL Connector/J (8.0.20) to set up a replication topology (master ⭢ slave)
[/home/wfranchi/MySQL/mysql-8.0.20/bin/mysqladmin, --protocol=TCP, --port=3306, --user=root, ping] [/home/wfranchi/MySQL/mysql-8.0.20/bin/mysqld, --no-defaults, --port=3306, --basedir=/home/wfranchi/MySQL/mysql-8.0.20, --datadir=/home/wfranchi/GitHub/sample-java-mysql-connector/bdApp1/data, --socket=socket, --log-error=/home/wfranchi/GitHub/sample-java-mysql-connector/bdApp1/log.txt] wait...
Author   wagnerjfr
🌐
ZetCode
zetcode.com › db › mysqljava
MySQL Java - MySQL programming in Java with JDBC
It covers the basics of MySQL programming in Java with JDBC. ZetCode has a complete e-book for MySQL Java: MySQL Java programming e-book. In this tutorial, we use the MySQL Connector/J driver. It is the official JDBC driver for MySQL. The examples were created and tested on Ubuntu Linux.
🌐
Software Testing Help
softwaretestinghelp.com › home › mysql › mysql connector tutorial: java and python connector examples
MySQL CONNECTOR Tutorial: Java And Python Connector Examples
April 1, 2025 - ... Answer: MySQL connector is nothing but a small piece of software (or can be called an API implementation) for the interface exposed by the target programming language. For example, JDBC in the case of Java.
🌐
Maven Repository
mvnrepository.com › artifact › mysql › mysql-connector-java
Maven Repository: mysql » mysql-connector-java
April 18, 2023 - MySQL Connector/J is a JDBC Type 4 driver, which means that it is pure Java implementation of the MySQL protocol and does not rely on the MySQL client libraries.
🌐
Javatpoint
javatpoint.com › example-to-connect-to-the-mysql-database
Java Database Connectivity with MySQL
Example to connect to the mysql database with examples on Driver, DriverManager, Connection, Statement, ResultSet, PreparedStatement, CallableStatement, ResultSetMetaData, DatabaseMetaData, RowSet, Store Image, Fetch Image, Store file, Fetch file etc.
🌐
MySQL
dev.mysql.com › doc › connectors › en › connector-j-overview.html
MySQL :: Connectors and APIs Manual :: 3.1 Overview of MySQL Connector/J
Connector/J 8.0 provides ease of development features including auto-registration with the Driver Manager, standardized validity checks, categorized SQLExceptions, support for large update counts, support for local and offset date-time variants from the java.time package, support for JDBC-4.x ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-database-connectivity-with-mysql
Java Database Connectivity with MySQL - GeeksforGeeks
October 4, 2025 - Java JDK installed on your system. ... Search for MySQL Community Downloads. Go to Connector/J.