preparedStatement 的两种使用方式:
方式1:使用preparedStatement选择数据,读取数据:
使用preparedStatement插入数据的数据库:public boolean saveComment(Comment comment) { Connection connection = DBUtil.getConn(); String sql = "insert into comment values (null,?,?,?,?)"; PreparedStatement preparedStatement = null; boolean flag = false; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, comment.getCommenttext() + ""); preparedStatement.setString(2, comment.getCommenttime() + ""); preparedStatement.setString(3, comment.getUserid() + ""); preparedStatement.setString(4, comment.getArticleid() + ""); int isOk = preparedStatement.executeUpdate(); if (isOk > 0) { return !flag; } else { return flag; } } catch (SQLException e) { e.printStackTrace(); } DBUtil.close(connection, null, preparedStatement, null); return flag; }
方式2:
public int insert(Orders orders){ // try {// testSessionDowork();// } catch (Exception e) {// // TODO Auto-generated catch block// e.printStackTrace();// } Session session = getSession();// session.beginTransaction().begin();; try { session.doWork(new Work() { @Override public void execute(Connection arg0) throws SQLException { //通过JDBC 原生API 进行操作,效率最高,速度最快// String sql = ""; //preparedStatement = arg0.prepareStatement(sql);//准备执行语句 //int Res = statement.executeUpdate(sql); if(orders == null){ return ; } DateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //创建一个格式化日期对象 String currentTime = simpleDateFormat.format(orders.getCreateTime()); //格式化后的时间 String sql = "INSERT INTO orders " + "" + " ( total, create_time, STATUS, pay_status, member_id, ship_area, ship_address, ship_mobile ) " + " VALUES " + " " + " ( "+orders.getTotal()+", '"+currentTime+"', '"+orders.getStatus()+"', '"+orders.getPayStatus()+"', '"+orders.getMemberId()+"', '"+orders.getShipArea()+"', '"+orders.getShipAddress()+"', '"+orders.getShipMobile()+"' )"; System.out.println("orders insert sql :" + sql); number = preparedStatement.executeUpdate(sql); System.out.println(number > 0 ? "插入数据成功" : "插入数据失败"); } }); // session.getTransaction().commit(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ doClose(null, preparedStatement, rs); } return number; }
注意:
方式1:
int isOk = preparedStatement.executeUpdate(); 没有参数sql
方式2:
number = preparedStatement.executeUpdate(sql);有参数sql
参考链接: