Quick Enquiry

Please type below

captcha

c
23 Apr 2016

How to Connect to a MySQL RDBMS from Java with JDBC

The standard way of working against a relational database from Java is by using the JDBC API.

(the Java Database Connectivity API). This API allows you to access any relational database from Java, no matter whether you’re on Linux, Solaris or Windows. As long as there’s a JDBC driver for the database, you can use the same standard API to access it.

To give you a kickstart in using MySQL from your applications, we decided to provide a little tutorial on this subject.

Prerequisites

When you’re going to access a relational db from Java, you’ll need the following:

  • * JDBC API (part of the JDK)
  • * JDBC Driver for your database

(or the JDBC-ODBC bridge driver from Sun that comes with the JDK)

The JDBC driver for MySQL can be found at MySQL download page …

Using the JDBC Driver

In order to use the JDBC driver, you just need to put it on your classpath, or installing it as a Java extension library.

to put it on the classpath:

WINDOWS:

set classpath=c:\path\to\jar\mysql-connector-java-2.0.14-bin.jar;%classpath%

UNIX:

export CLASSPATH=/path/to/jar/mysql-connector-java-2.0.14-bin.jar:$CLASSPATH

(of course, you’ll need to change the folders to the folder you put the JAR into)

if you put it in your jre/lib/ext folder of your JDK/JRE, it will also be found automatically.

 Preparing the test database

In order to let our little demo program do it’s job, you’ll need to create a database on the MySQL instance.

Startup the mySQL console (mysql.exe on windows, mysql.sh on unix).

use:

create database test;

Compiling and running the test program

Compile the test program:

javac TestMySQL.java

Run it by the following command:

java TestMySQL localhost test

(the first argument is the host with the MySQL server, the second argument is the name of the database you created for our test program).

If an error occurs, the most probable reason is that the MySQL JDBC driver is not on your classpath, so it can’t be found.

If you have some questions/remarks regarding this article, please feel free to comment below.

Comments

Write a Comment

No comment posted.