Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

Friday, May 14, 2010

JDBC MySQL snippet

I'm working on my database project. Here is a tips to connect java with MySQL in Ubuntu. I downloaded MySQL Java connector with Synaptic. The downloaded file is mysql-connector-java-5.1.10.jar and located at /usr/share/java path. I copied that file to my java home's /jre/lib/ext directory, which is /usr/lib/jvm/java-6-sun-1.6.0.20/jre/lib/ext

I created a database with this command in mysql :

create database test;
create table Name (FirstName char(10),LastName char(10));
insert into Name values ("Md. Rezaur","Rahman");

Now I used this code to test my connection:


import java.sql.*;

public class JdbcExample1 {

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

try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql:///test", "sajol", "123456");
if(!con.isClosed()){
System.out.println("Successfully connected to MySQL server...");
Statement s = con.createStatement ();
s.executeQuery("select FirstName,LastName from Name");
ResultSet rSet = s.getResultSet();
int count = 0;
while (rSet.next ())
{
String FirstName = rSet.getString ("FirstName");
String LastName = rSet.getString ("LastName");
System.out.println (" First Name = " + FirstName+ ", Last Name = " + LastName);
++count;
}
rSet.close ();
s.close ();
System.out.println (count + " rows were retrieved");
}
}

catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
}
finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}
}
}