Tuesday, August 23, 2005

MySQL database connector/J

To use JDBC to connect to MySQL, should do the following:

1. insatll connector(JDBC driver). On debian, there is a libmysql-java package, or we can download from Mysql.com. Then, the fast and dirty way is copy the mysql-connector-java-[version]-bin.jar file to the $JAVA_HOME/jre/lib/ext. After that, in Eclipse--> preference --> build path, we can see this jar file.

2. the following sample code should work fine:

import java.net.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class HelloJdbc extends Frame{

Choice s;
Connection con;
Statement st;

public HelloJdbc(){
s = new Choice();
String url = "jdbc:mysql://localhost:3306/trilBlog";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url,"username","password");
st = con.createStatement();
String SQL = "SELECT * FROM Users";
ResultSet rs = st.executeQuery(SQL);
while(rs.next()){
s.addItem(rs.getString(3));
}
}catch(Exception e){
System.out.println("hey, cannot connect to database");
}
add(s);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Frame f = new HelloJdbc();
f.setSize(300,300);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent evt){
System.exit(0);
}
});
f.show();
}
}