How do you connect to a MySQL database in Java?
When I try, I get
java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
Or
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Or
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
Here's a step by step explanation how to install MySQL and JDBC and how to use it:
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
.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.The
.
is just there to add the current directory to the classpath as well so that it can locatecom.example.YourClass
and the;
is the classpath separator as it is in Windows. In Unix and clones:
should be used.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 an user for Java and grant it access. Simply because using
root
is a bad practice.Yes,
java
is the username andpassword
is the password here.Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:
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 uselocalhost
. It can also be an IP address like127.0.0.1
. If you encounter connectivity problems and using127.0.0.1
instead oflocalhost
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 default3306
.databasename
: The name of the database you'd like to connect to. That'sjavabase
.So the final URL should look like:
Test the connection to MySQL using Java. Create a simple Java class with a
main()
method to test the connection.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). 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:Note that the
newInstance()
call is not needed here. It's just to fix the old and buggyorg.gjt.mm.mysql.Driver
. Explanation here. If this line throwsClassNotFoundException
, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.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
orConnection timed out
or a MySQL specificCommunicationsException: Communications link failure
, then it means that the DB isn't reachable at all. This can have one or more of the following causes:To solve the one or the other, follow the following advices:
ping
.my.cnf
of MySQL DB.--skip-networking option
.finally
.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 theConnection
in atry-with-resources
statement. Or if you're not on Java 7 yet, explicitly close it infinally
of atry-finally
block. Closing infinally
is just to ensure that it get closed as well in case of an exception. This also applies toStatement
,PreparedStatement
andResultSet
.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 for the DB connection is a bad approach. See among other questions: http://stackoverflow.com/q/9428573/. This is a #1 starters mistake.
Short and Sweet code.
For SQL server 2012
You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.
Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA
DriverManager
is a fairly old way of doing things. The better way is to get aDataSource
, either by looking one up that your app server container already configured for you:or instantiating and configuring one from your database driver directly:
and then obtain connections from it, same as above:
Initialize database constants
Create constant properties database username, password, URL and drivers, polling limit etc.
Initialize Connection and Properties
Once the connection is established, it is better to store for reuse purpose.
Create Properties
The properties object hold the connection information, check if it is already set.
Connect the Database
Now connect to database using the constants and properties initialized.
Disconnect the database
Once you are done with database operations, just close the connection.
Everything together
Use this class
MysqlConnect
directly after changing database_name, username and password etc.How to Use?
Initialize the database class.
Somewhere else in your code ...
This is all :) If anything to improve edit it! Hope this is helpful.