How to Connect to MySQL database in Java with Example

In this tutorial, You will learn how to connect to MySQL database from Java program and running SELECT and INSERT queries to retrieve and update data with step by step guide. In order to connect and access the MySQL database from Java, you can use JDBC (Java Database Connectivity) API, which is bundled in JDK itself. JDBC allows you to connect to any database like Oracle, SQL Server, or MySQL, provided you have the vendor's implementation of the JDBC driver interface, which is required to connect the database. You can connect to MySQL from Java by using MySQL's Type 4 JDBC driver which is bundled in mysql-connector-java-5.1.23-bin.jar. It's type 4, pure Java driver, which means you don't need any native library or JDBC ODBC bridge, all you need is to put this JAR in your classpath.


This JAR contains "com.mysql.jdbc.Driver" which is the key for making database connection from Java program to MySQL DB. If this JAR is not present in the classpath, then while running this program you will get java.lang.ClassNotFoundException: com.mysql.jdbc.Driver, so always make sure you have this JAR in the classpath.


By the way, if you are looking for some good book to master JDBC programming in Java, I suggest you take a look at the Complete JDBC Programming course on Udemy. It's a great course of direct classroom lectures and covers JDBC in-depth and cover two of the most popular database SQL Server 2008 and Oracle.


This book also teaches you how to work in the Netbeans Integrated environment, similar to our example, and provides all necessary tools and knowledge to handle database programming in Java. An ideal book for graduate and undergraduate students, as well as database programmers and software engineers.


Connecting to MySQL database using JDBC

In order to connect to MySQL database, you need four things :

  1. JDBC URL (jdbc:mysql://localhost:3306/test)

  2. Username ("root")

  3. Password ("root")

  4. Database with table to demonstrate query (Book database with few books in test database)


The JDBC URL for MySQL database starts with "jdbc:mysql" that's the protocol connection is using to connect, followed by host and port where your MySQL database is running. In our case, I am running MySQL server in localhost, which by default listens to port 3306, unless you change it during installation.


Next part is "test" which is an empty database which comes with MySQL. I have created a Book table into this database for our example purpose. If you want, you can also create the same table by using following SQL :

CREATE TABLE `books` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `author`