Sharing The Knowledge

My Photo
Name:
Location: Allahabad, Uttar Pradesh, India

I am a simple guy and prefer to keep life simple

Wednesday, July 26, 2006

Getting started with Mysql and Connecting it with JDBC

Well I am gonna discuss here my learning experience with mysql.
I don't remember from where I got the setup for mysql. ut I think its not a big deal its freely available on net . The main problem is how to use it..

In the time of installation it will ask about the desired location as example I have choosed c:\mysql . then I need a a Mysql Connector/J.

For example I have downloaded Connector/J 3.1
http://dev.mysql.com/downloads/connector/j/3.1.html

And I downloaded Zip archive my system have Windows XP
I extracted the zip archive which contain a pdf in docs folder (really good one).
and a Jar file .

I included that jar file in my classpath. I was using Kawa IDE so it is very easy to configure the classpath.You have to find a other way if you wanna do it by system .you may try systm environment variables in Window XP for that..

Bow I think its sufficient to write a programme for connecting database through jdbc driver.


A programme for testing the connection


import java.sql.*;

public class Connect
{
public static void main (String[] args)
{
Connection conn = null;

try
{
String userName = "user";
String password = "passwd";
String url = "jdbc:mysql://localhost/mysql";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}

Sample output


Database connection established

Database connection terminated

Here mysql is the name of my database in
jdbc:mysql://localhost/mysql

and the user name password is user/passwd

I hope its enough for a starter