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 FilesJavajdk1.6.0_01jrelibext

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:
[code]
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 {
Class.forName(m_Driver);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}

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 ";
query+=tablename;

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

//Loop through the results
while (m_ResultSet.next()) {

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

}//end for while loop

}
catch (SQLException ex) {
ex.printStackTrace();
System.out.println(query);

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

}

finally {

try {
if (m_ResultSet != null)
m_ResultSet.close();
if (m_Statement != null)
m_Statement.close();
if (m_Connection != null)
m_Connection.close();
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
[/code]