目录
1.预编译命令对象
特点及作用:
1.继承自statement接口
2.预编译的sql语句对象
3.对sql语句进行预编译,存储到PrepareStatement对象中,可以多次执行命令,提高效率
4.杜绝sql注入式攻击,安全性高。使用的时参数式的sql命令
使用PrepareStatement实现数据库操作
@Test
public void test1(){
String bname = "水浒传";
String author = "施耐庵";
double price = 25.98;
String prodate = "2015-12-23";
Connection con = null;
PreparedStatement pst = null;
String sql = "insert into books" +
" (bname,author,price,prodate)" +
" value" +
" (?,?,?,?)";
try {
con = BaseDAO.getConnection();
pst = con.prepareStatement(sql);
Object[] parms = {bname,author,price,prodate};
// 这里对预编译的参数设置进行了封装
// pst.setObject(1,bid);
BaseDAO.setParams(pst,parms);
int count = pst.executeUpdate();
System.out.println(count);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
BaseDAO.closeAll(con,pst,null);
}
}
@Test
public void test2(){
String name = " ' jk # ";
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
String sql = "select * from books" +
" where bname = ?";
try {
con = BaseDAO.getConnection();
pst = con.prepareStatement(sql);
pst.setObject(1,name);
System.out.println(pst);
rs = pst.executeQuery();
while (rs.next()){
for (int i = 1; i <=5 ; i++) {
System.out.print(rs.getObject(i)+" ");
}
System.out.println();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
BaseDAO.closeAll(con,pst,rs);
}
}
方法 | 说明 | |
executeUpdate() | 执行增删改操作 | 返回影响行数 |
executeQuery() | 执行查询操作 | 返回ResultSet结果集对象 |
setString(参数索引,参数值) | 设置sql中的?参数/替换位字符串数据 | |
setObject(参数索引,参数值) | 设置sql中的?参数/替换位对象数据 |
//设置参数
public static void setParams(PreparedStatement pst,Object[] params){
if (params==null){
return;
}
//设置参数
for (int i = 0; i < params.length; i++) {
try {
pst.setObject(i+1,params[i]);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}