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.
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:
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
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
Once you have established your connection, you can query your MySQL database using Java. To create and execute a query, use JDBC’s
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
String sql = “INSERT INTO Users(username, email) VALUES(?,?) RETURNING *”; String username = “Arctype”; String email = “email@example.com”; PreparedStatement myStmt = myConn.prepareStatement(sql); myStmt.setString(1, username); myStmt.setString(2, email); ResultSet results = myStmt.executeQuery();
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.