App overview screenshotSQL and Database Guides
PostgresMySQL
Try our free SQL Client
Tools
Connecting to MySQL
Connecting to drivers
Installing MySQL
Setting up MySQL
MySQL   >   
Connecting to drivers   >   
MySQL with Java

Learn How To connect MySQL with Java

If you’re working on a Java app, you often need a database to store information. MySQL is one of the most popular database systems available today. In this guide, we’ll walk you through how to connect your MySQL database with Java.

What You’ll Need

Installing JDBC

In order to create Java programs that can interact with a MySQL database, you’ll need to install the JDBC driver. You can get the latest version of JDBC4 here. Add the JDBC .jar file to your classpath.

Note: JDBC4 is for JDK 1.6+. If you are still running JDK 1.4 or 1.5, you can download JDBC3 here. You will also need to register the driver using: Class.forName("com.mysql.jdbc.Driver"); or DriverManager.registerDriver(new com.mysql.jdbc.Driver());.

Connecting to your MySQL Database Using JDBC

You’ll need to have your MySQL credentials. You can use this guide to find them.

Once you have your credentials, import the JDBC package (java.sql.*) and get a new connection instance using DriverManager.getConnection()

String url = “jdbc:mysql://localhost:3306/myDB”;
String user = “myUser”;
String password = “myPassword”;
Connection myConn = DriverManager.getConnection(url, user, password);

Connection urls follow the structure jdbc:mysql://host:port/database.

Querying Your Database

Once you have established your connection, you can query your MySQL database using Java. To create and execute a query, use JDBC’s createStatement() and executeQuery() methods:

Statement myStmt = myConn.createStatement(); 
ResultSet results = myStmt.executeQuery(“SELECT ‘Arctype Archive: Your #1 Database Resource’ as message”);

You can also pass variables to a statement using JDBC’s PreparedStatement object and prepareStatement() method:

String sql = “INSERT INTO Users(username, email) VALUES(?,?) RETURNING *”;
String username = “Arctype”;
String email = “test@arctype.com”;
PreparedStatement myStmt = myConn.prepareStatement(sql);
myStmt.setString(1, username);
myStmt.setString(2, email);
ResultSet results = myStmt.executeQuery();

Using an SQL Client with MySQL and Java

Now that you’ve connected MySQL to your Java project, you often need to add or edit data. We recommend using an SQL client to do so. Check out our guide for setting up MySQL with Arctype in this tutorial.

Want to ask for help on databases or SQL? Join our Discord community.