Search This Blog

Thursday, August 26, 2010

Connect Java with MySql database

This is a simple Java code which connects to a mysql database, adds and retrieves data from it. For that purpose we will need the mysql driver for java, which can be downloaded here : MysqlConnectorJava
Extract it to a appropriate location (preferably where java is installed)
The folder contains the driver file named mysql-connector-java-5.1.8-bin.jar whose location has to be added to the CLASSPATH so that java finds it.

In windows CLASSPATH can be accessed from My Computer(right click)->properties->Advanced tab->Environment Variables. In system variables if you see a variable named CLASSPATH, edit it and append the driver path for ex. 'C:\j2sdk1.4.2_15\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar' to the existing value with ';' seperating each entry in classpath.

Or open the command prompt and type -> 

set CLASSPATH=%CLASSPATH%;C:\j2sdk1.4.2_15\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar

replacing my path with yours. Type set CLASSPATH to verify if it has been added to CLASSPATH variable.

In linux shell>
setenv CLASSPATH /path/mysql-connector-java-[ver]-bin.jar:$CLASSPATH

The following code is supposed to create a database, add data to it, read the added data and finally drop the database. The database user is 'root' with password 'password'

The Code


No comments:

Post a Comment