How To Connect To MySQL Database in Java With Example
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 MySQL database from Java, you can use
JDBC (Java Database Connectivity) API, which is bundled in JDK itself. JDBC allow you
to connect to any database e.g. Oracle, SQL Server or MySQL, provided you have the
vendor's implementation of JDBC driver interface, which is required to connect
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 to take a look
at Practical Database Programming with Java By Ying Bai. This is one of the relatively
latest book on JDBC and cover two of the most popular database SQL Server 2008 and
Oracle. This book also teaches you how to work in 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.
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 :
and you can use following SQL to populate table with some good books :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
} finally {
//close connection ,stmt and resultset here
try { con.close(); } catch(SQLException se) { /*can't do anything */ }
try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
}
}
}
When I again ran the Java program after including MySQL JDBC driver in Classpath, I
was greeted with following error, because I had included table name also in the JDBC
URL String as "jdbc:mysql://localhost:3306/test/book", let's try to run
after removing table from JDBC String
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorI
mpl.java:62)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructor
AccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
Couple of things to pay attention here. See the rs.getInt(1) method call, well
that is to retrieve an integer column, which is "id" in our case. In JDBC, column index
begin with 1, so rs.getInt(1) will read first column as Integer. It will
throw InvalidColumnIndexException if we provide invalid column index, as
many Java developer mistakenly provide "0" for first column i.e. rs.getInt(0).
Accessing columns with index is risky, its better to use column name instead of
indexes i.e. rs.getInt("id") will return value of id column. It is also one of the
JDBC best practices you will learn in my post 10 JDBC best practice for Java
developers . Similarly getString() is used to read String or VARCHAR columns. The
loop will run until rs.next() return false, when number of rows comes to an end.
This query returns 2 rows and that's why the loop runs twice, printing details of
two books loaded from MySQL database.
Once you run the program, you can go back and check the database. This time you
will see 3 records in your book table, as shown below :
That's all about how to connect to MySQL from Java program. Once you are able to
make a successful connection you can run SELECT, INSERT, DELETE or UPDATE query
just like you do using MySQL command line client or MySQL GUI. Like connecting to
any other database, we have used Connection object to make connection and
ResultSet object to get the result of our SQL Query. Just make sure that your MySQL
Server is started and running before you connect and mysql-connector-java-5.1.17bin.jar is in CLASSPATH to avoid nasty ClassNotFoundException.
Once you are comfortable with connecting, retrieving data and inserting data, next
step is to learn how to use PreparedStatement in Java to prevent SQL injection. In a
production system, you should always use PreparedStatement and bind variables.
If you like this JDBC tutorial and hungry to learn more about connecting and operating
database from Java application, you may like following amazing articles too :
Resources :
If you don't have MySQL database, you can download from here
If you don't have MySQL JDBC driver, you can also download the mysqlconnector-java-5.1.17-bin.jar file from here.
You can get recommended JDBC book, Practical Database Programming with
Java By Ying Bai here