Pages

Monday, 6 June 2011

JDBC and MySQL

Steps to connect to a MySQL database from Java


1. Import

import java.sql.*;
import javax.sql.*;

2. Declare a Connection type in the class:

Connection conn;

3. Add a method to establish connection. Assume the name of the database is GameIF, and the username/password are the default values i.e username is root and there is no password.


private void connect()
{
String dbUrl = "jdbc:mysql://localhost/GameIF";
String dbClass = "com.mysql.jdbc.Driver";
String username="root";
String password="";

try
{
Class.forName(dbClass).newInstance();
conn = DriverManager.getConnection(dbUrl,username,password);
}
catch(Exception e)
{
System.out.println(e);
}
}



3.  Add a function that tears down the connection:


private void disconnect()
{
if (conn != null)
{
try
{
conn.close();
}
catch (Exception e) {}
}
}


4. Writing/Executing a query: A query may be of two types:

(a) One that returns a result set (e.g: SELECT query)

(b) One that returns no result set (e.g: DROP, CREATE, INSERT, UPDATE)

We'll see examples for both types:

(a) SELECT

connect( );

String uname, steps;

String query = "select * from `scores`";
try
{
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
uname = rs.getString("username");
steps = rs.getInt("steps");
System.out.println("Username: "+uname+"\tSteps: "+steps);
}
rs.close();
st.close();
}
catch(Exception e) {
System.out.println(e);
}


disconnect( );


(b) INSERT


connect( );


Statement s;
String query = "insert into `scores` (`game` , `username` , `steps`) values ('NUMBERJUMBLE','Tups',56)";
try
{
s = conn.createStatement( );
s.executeUpdate(query);
s.close( );
}
catch(Exception e)
{
System.out.println(e);
}


disconnect( );




And, we're done!
However, a very common exception is encountered if you are building a standalone application:

java.lang.ClassNotFoundException

To fix this:
1. Download the mysql connector jar files (A straightforward google search!)
2. Add the jar files (format mysql-connector-java-<version>-bin.jar) to the following two folders:
         <your jdk directory>/jre/lib
         <your jdk directory>/jre/lib/ext

If you are using netbeans or another IDE, copy the files and restart!

Cheers!


1 comment:

  1. This was a great tutorial! the exception was killing me and nothing else was working. Great help.

    Alexx

    ReplyDelete