Connecting with MySQL in JAVA

Sometimes we need to use database(MySQL).So,we must connect our interpreter to the existing MySQl.For this we need JDBC driver to install it.In netbeans IDE jdbc driver is built in.But to make this working, we must have a mysql connector,which is a jar file in our system.

We must download a mysql-connector-java-5.0.8-bin.jar and keep it to
C:\Program Files\Java\jdk1.6.0_01\jre\lib\ext\

In java programming, before coding we must established a connection between interpreter and MySQL.

at first we must import some built in packages.they are:

import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;

//now finally in our main job i.e establishing the connection

Connection m_Connection = null;
Statement m_Statement = null;
ResultSet m_ResultSet = null;

String m_Driver ="com.mysql.jdbc.Driver";
String m_Url = "jdbc:mysql://localhost:3306/databasename";

//Loading driver
try {
catch (ClassNotFoundException ex) {

String query = "";
try {

//Create connection object
m_Connection = DriverManager.getConnection(m_Url, user, password);

//Create Statement object
m_Statement = m_Connection.createStatement();
query = "SELECT * FROM ";

//Execute the query
m_ResultSet = m_Statement.executeQuery(query);
String s,t="";

//Loop through the results
while ( {

s=m_ResultSet.getString(1); //here 1 means value of first coloumn

}//end for while loop

catch (SQLException ex) {

catch (Exception e) {
System.err.println("Error: " + e.getMessage());


finally {

try {
if (m_ResultSet != null)
if (m_Statement != null)
if (m_Connection != null)
catch (SQLException ex) {

Posted on April 3, 2011, in Database and tagged , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: