Wednesday, October 24, 2007

How do you connect to a MySql Database using JDBC?

Recently some newbie asked me a simple question of connecting to MySql database using JDBC.Here is a code snippet for that.The important thing here is to ensure that you have added MySql database driver classes(mysql.jar) in your classpath. Here goes the code snippet:
import java.sql.*;

public class MySqlConnect {


public static void main (String[] args)
{
Connection connection = null;

try
{
String userName = "root";
String password = "bunty";
String url = "jdbc:mysql://localhost:3306/systdb";

Class.forName ("com.mysql.jdbc.Driver").newInstance ();

connection = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Connection to database server cannot be establish");
}
finally
{
if (connection != null)
{
try
{
connection.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { System.out.println ("These connection errors can be ignored."); }
}
}
}
} 

2 comments :

Milan Vachhani on March 11, 2011 at 10:47 PM said...

Thank You....
It works fine...

mohit sachan on November 10, 2011 at 2:49 AM said...

yes, thaks alot
it is working right......

 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2017. Reads: best tracker