jSP 通过JDBC操作数据库的一些坑
最近想着给公司的一些账号密码做一个管理,就想做一个内部网站。在处理数据库的时候,jdbc的PreparedStatement 给了我很多坑。在此记录一下:
1,查询:比较顺利
String sql = "select * from pa_yc";
pstmt=conn.prepareStatement(sql);
rSet=pstmt.executeQuery();
while (rSet.next()) {
RemoteControlMsg remoteControlMsg=new RemoteControlMsg();
int id=rSet.getInt("id");
}
2,更新:坑 一堆堆
第一个坑:
String sql="UPDATE pa_yc set (pc_name = ?,xrk_no=?,xiangrikui_pwd=?,todesk_no=?,todesk_pwd=?) WHERE id = ?;";
Object[] objects = new Object[] {remote.getId(),remote.getPc_name(),remote.getXiangrikui_no(),remote.getXiangrikui_pwd(),remote.getTodesk_no(),remote.getTodesk_pwd()};
pstmt = conn.prepareStatement(sql1);
for(int i=0;i<objects.Length();i++){
pstmt.setObject(i+1,objects[i]);
}
正常情况下,这种方式是可以的。但是我用的时候始终有错,折磨了好久,最后发现 sql语句是有限制的。字符串太长就会被截断舍弃。
然后我想着分开更新信息:
String sql1="update pa_yc set pc_name =? where id =?;";
String sql2="update pa_yc set xrk_no=? WHERE id =?";
String sql3="update pa_yc set xrk_pwd=? WHERE id =?";
String sql4="update pa_yc set td_pwd=? WHERE id =?";
String sql5="update pa_yc set td_no=? WHERE id =?";
Object[] objects = new Object[] {remote.getId(),remote.getPc_name(),remote.getXiangrikui_no(),remote.getXiangrikui_pwd(),remote.getTodesk_no(),remote.getTodesk_pwd()};
try {
pstmt = conn.prepareStatement(sql1);pstmt.setObject(1, objects[1]);pstmt.setObject(2, objects[0]);
pstmt.execute();pstmt.close();pstmt=null;
pstmt = conn.prepareStatement(sql2);pstmt.setObject(1, objects[2]);pstmt.setObject(2, objects[0]);
pstmt.executeUpdate();pstmt.close();pstmt=null;
pstmt = conn.prepareStatement(sql3);pstmt.setObject(1, objects[3]);pstmt.setObject(2, objects[0]);
pstmt.executeUpdate();pstmt.close();pstmt=null;
pstmt = conn.prepareStatement(sql4);pstmt.setObject(1, objects[4]);pstmt.setObject(2, objects[0]);
pstmt.executeUpdate();pstmt.close();pstmt=null;
pstmt = conn.prepareStatement(sql5);pstmt.setObject(1, objects[5]);pstmt.setObject(2, objects[0]);
pstmt.executeUpdate();pstmt.close();pstmt=null;
}
坑的地方:1,sql 中,set xxx = ? 这个地方 不能有”()“
2,在每一个pstmt.executeUpdate();后面,都需要pstmt.close();pstmt=null;
3,增加:比较顺利,按照正常的方式
String sql = "insert INTO pa_yc(pc_name,xrk_no,xrk_pwd,td_no,td_pwd) values (?,?,?,?,?);";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, remoteControlMsg.getPc_name());
pstmt.setString(2, remoteControlMsg.getXiangrikui_no());
pstmt.setString(3, remoteControlMsg.getXiangrikui_pwd());
pstmt.setString(4, remoteControlMsg.getTodesk_no());
pstmt.setString(5, remoteControlMsg.getTodesk_pwd());
pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
Close();
}