import java.sql.*;
import java.util.*;
public final class Mysql{
private Connection conn = null;
// private Statement st = null;
ArrayList res = new ArrayList();
private PreparedStatement ps = null;
private ResultSet rs = null;
private String url = "jdbc:mysql://localhost:3306/test";
private String user = "root";
private String passwd = "";
private static final String name = "com.mysql.jdbc.Driver";
// private String driver = "org.gjt.mm.mysql.Driver";
static {
try{
// com.mysql.jdbc.Driver d = new com.mysql.jdbc.Driver();
Class.forName(name);
// DriverManager.registerDriver(new com.mysql.jdbc.Driver());
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
}
public Connection getConn(){
try{
conn = DriverManager.getConnection(url,user,passwd);
}catch(SQLException sqle){
conn = null;
sqle.printStackTrace();
}finally{
return conn;
}
}
public ArrayList getRs(String sql){
try{
// st = conn.createStatement();
conn = getConn();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
System.out.println(conn);
if(rs != null){
while(rs.next()){
ArrayList record = new ArrayList();
record.add(rs.getInt("id"));
record.add(rs.getString("name"));
record.add(rs.getString("sex"));
record.add(rs.getString("hobby"));
res.add(record);
}
}
}catch(SQLException sqle){
sqle.printStackTrace();
}finally{
try{
if(rs != null){
rs.close();
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
return res;
}
}
public ArrayList getRs(ArrayList al, int id){
ArrayList tmp = null;
for(int i=0; i<al.size(); i++){
if(id == ((ArrayList)al.get(i)).get(0)){
tmp = (ArrayList)al.get(i);
}
}
return tmp;
}
public void closeAll(){
try{
if(rs != null){
rs.close();
}
}catch(SQLException sqle){
sqle.printStackTrace();
}finally{
try{
if(ps != null){
ps.close();
}
}catch(SQLException sqle){
sqle.printStackTrace();
}finally{
try{
if(conn != null){
conn.close();
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
}
}
}
public void showRs(ArrayList al){
if(al != null){
for(int i=0; i<al.size(); i++){
System.out.print(((ArrayList)al.get(i)).get(0) + " ");
System.out.print(((ArrayList)al.get(i)).get(1) + " ");
System.out.print(((ArrayList)al.get(i)).get(2) + " ");
System.out.print(((ArrayList)al.get(i)).get(3) + " ");
System.out.println(" ");
}
}
}
}
import java.sql.*;
import java.util.*;
public class Test{
public static void main(String[] args){
Mysql m = new Mysql();
// m.init();
String sql = "SELECT * FROM stu";
ArrayList rs = m.getRs(sql);
if(rs != null){
System.out.println(rs.size());
for(int i=0; i<rs.size(); i++){
System.out.print(((ArrayList)rs.get(i)).get(0) + " ");
System.out.print(((ArrayList)rs.get(i)).get(1) + " ");
System.out.print(((ArrayList)rs.get(i)).get(2) + " ");
System.out.print(((ArrayList)rs.get(i)).get(3) + " ");
System.out.println(" ");
}
}
ArrayList a = m.getRs(rs,3);
if(a != null){
for(int j=0 ;j<4; j++){
System.out.println(a.get(j)+" ");
}
}
m.closeAll();
}
}