Software Development

How to connect Java to MySQL using JDBC

This post shows how to connect Java to MySQL using JDBC. Therefore, nothing fancy here. Just JDBC basics.

MySQL JDBC Requirements

We used the following items for this post. Although we can use newer versions, the Java JDBC codes pretty much stay the same. For example, the codes would still work on Windows 10, MySQL 8.x, and the appropriate version of MySQL Java connector. In fact, it does not matter which Windows version we use because Java is platform-independent! We could even run our codes in Linux.

  • Windows 7 Professional SP1
  • MySQL 5.6.16 – Community Server (GPL)
  • MySQL Java Connector 5.1.34

Configure a MySQL Instance

For our Java codes to work, we need a MySQL server running. We could create one using MySQL Docker image.

Java Codes

The JDBC API allows us to connect to virtually any database with its respective Java Connector. The following Java codes show how to connect to MySQL using the JDBC API and Java Connector.

First, we could have an empty static method like the main method to start with.

Second, we load the appropriate MySQL Java Connector driver class. Note that this operation is sluggish, and we should not use it in production. When you have learned enough Java and JDBC, you realize that there are other efficient ways to load the MySQL Java connector driver class. For now, we stick to using this technique.

Third, we create MySQL connections using the MySQL Java Connector driver we have loaded. Notice we pass some parameters that we can get from our MySQL server. For example, the port number and the MySQL database. Also, we pass a database user’s credentials that our Java application will use to interact with the database.

Fourth, we create Statement objects from Connection objects in Java.

JDBC Connection objects allow us to retrieve data from or update/insert data to MySQL. We supply SQL commands to these objects to do our bidding. For example, we could retrieve rows of data from MySQL using the following line of Java codes.

When we put the codes together plus some more, we will have a Java program the uses the JDBC API to use MySQL. Consider the complete Java codes below.

This post is (now) part of a reboot Java tutorial.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like