Accessing MySQL Database Table Using Type-4 Driver In Java

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click  View Source “View Source” on the right of this code snippet.

Background and Explanation of the code


This program connects to MySQL database using Type-4 JDBC driver. Download the driver JAR file from the following link:http://dev.mysql.com/downloads/connector/j/

Download mysql-connector-java-5.1.16.zip from above link and unzip it, you will find mysql-connector-java-5.1.16.jar into it. Put this JAR into the same directory where the DatabaseDemo.java is available.

Set the CLASSPATH upto the driver’s JAR file using following command:

CLASSPATH=%CLASSPATH%;./mysql-connector-java-5.1.16-bin.jar

Modify DatabaseDemo.java for correct values for databaseUser, databasePassword, databaseServerSystem and databaseName.

Create ‘Employee’ table in MySQL database using following script:

CREATE TABLE `test`.`Employee` (
`Id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(45) NOT NULL,
`Telephone` VARCHAR(45) NOT NULL,
PRIMARY KEY (`Id`)
)
ENGINE = InnoDB;

Insert some records into ‘Employee’ table for testing.

To compile the program: javac DatabaseDemo.java

To run the program: java DatabaseDemo

It will display all records of ‘Employee’ table on the console.