Statement 与 PreparedStatement都是jdbc内置对象,PreparedStatement相当于是Statement的扩展,用于弥补Statement无法将程序中的变量作为查询的缺陷
,。
例子:分别用statement 与 preparedStatement:
用Statement插入数据:
{
boolean f= false;
String sql="insert into alluser(password,username,pid) values('"+bean.getPassword()+"','"+bean.getUsername()+"','"+bean.getPid()+"')";
Connection conn = DBUtil.getConn();
Statement state =null;
try {
state = conn.createStatement();//实例化Statement对象
System.out.println(conn);
state.executeUpdate(sql);//执行指定的sql语句,如果SQL语句返回结果,则返回TRUE,否则返回false.
f=true;
}catch(Exception e) {
e.printStackTrace();//捕获异常语句
}finally {
DBUtil.releaseConnection(conn);
}
return f;
}
用PrepareStatement查询数据:
public ArrayList findAll(){
ResultSet rs=null;
ArrayList list=new ArrayList();
String sql="select * from reader";
try{
PreparedStatement preparedStatement = connection.prepareStatement(sql);
rs=preparedStatement.executeQuery();
while(rs.next()){
Reader reader=new Reader();
reader.setName(rs.getString(1));
reader.setidCard(rs.getString(2));
reader.setSex(rs.getString(3));
reader.setXueyuan(rs.getString(4));
list.add(reader);//向list链表中添加一个对象
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
closeConnection();
}catch(Exception e){
e.printStackTrace();
}
return list;
}
}