java从入门到精髓 - 数据库操作ResultSetLike
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ResultSetLike {
/**
* 取得相对路径的Connection
* @return
*/
public static Connection getConnection(){
Connection conn=null;
try{
String path="";
Class theClass = ResultSetLike.class;
//System.out.println(ConnTest2.class.getResourceAsStream("db.mdb"));
java.net.URL u= theClass.getResource("db.mdb");
String ChinesePath = URLDecoder.decode(u.getPath().substring(1,u.getPath().length()).replaceAll("%20", " "),"UTF-8");
//System.out.println(ChinesePath);
String url="jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="+ChinesePath;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//System.out.println("before connection");
conn=DriverManager.getConnection(url);
}catch(Exception ee){
System.out.println("connect db error:"+ee.getMessage());
}
return conn;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = ResultSetLike.getConnection(); //获得connection
try
{
Statement stmt = conn.createStatement(); //获得statement
ResultSet rs = stmt.executeQuery("select * from test where name like '%m%'"); //执行模糊查询
while(rs.next()) //取出相应的结果
{
String id = rs.getString("编号");
String name = rs.getString("name");
String age = rs.getString("age");
String address = rs.getString("address");
String memo = rs.getString("memo");
System.out.print("编号: "+id);
System.out.print(" name: "+name);
System.out.print(" age: "+age);
System.out.print(" address: "+address);
System.out.println(" memo: "+memo);
}
}catch(Exception e)
{
}
}
}