Java从入门到精通 - 数据库操作-PrepareStatementTest

import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PrepareStatementTest {

 /**
  * 取得相对路径的Connection
  * @return
  */
 public static Connection getConnection(){
   Connection conn=null;
   try{
        String path="";
           Class theClass = PrepareStatementTest.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 = PrepareStatementTest.getConnection();   //获得connection
  try
  {
   //Statement stmt = conn.createStatement();   //获得statement
   PreparedStatement stmt = conn.prepareStatement("select * from test where name =?");  //生成preparedStatement
   stmt.setString(1, "x");         //对第一个通配符赋值
   ResultSet rs = stmt.executeQuery();   //执行查询
   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)
  {
   
  }
 }

}

你可能感兴趣的:(Java从入门到精通 - 数据库操作-PrepareStatementTest)