public boolean insertOneCommentForOneArticleTestBatch(Comment comment,String author){
boolean flag=true;
DataBaseConnection dbc;
Connection con=null;
PreparedStatement pstmt;
dbc=new DataBaseConnection();
con=dbc.getConnection();

/******特别是这儿开始的几句 ***********************/ String sql="insert into comment(pdate,comment) value(now(),?)";          String sql2="update title set 评论数目=评论数目+1 where author=? ";

try { pstmt=con.prepareStatement(sql);
pstmt.setString(1, comment.getComment());
pstmt.executeUpdate(); pstmt=con.prepareStatement(sql2);
pstmt.setString(1, author);
pstmt.executeUpdate();
                  pstmt.close();

/*********************************************************************/

} catch (SQLException e) {
e.printStackTrace();
System.out.println("insertOneCommentForOneArticle(Comment comment)出错");
}finally{
dbc.close();
//实际上关的是con,
}
return flag;
}
public static void main(String agrs[]){

Comment comment=new Comment();
comment.setComment("TestBatch");

CommentDao cd=new CommentDao();


cd.insertOneCommentForOneArticleTestBatch(comment,"f");
}

解决方案 »

  1.   

    行啊,没什么不好的。
    如果需要事务控制,在前面加上conn.setAutoCommit(false);
    后面conn.commit();
    catch 里面 加上 conn.rollback();
    finally  里面加上 conn.setAutoCommit(true);
      

  2.   

    在方法中定义的局部变量[ PreparedStatement pstmt; ] ==>>[ PreparedStatement pstmt=null; ]必须赋初始值,否则报错!
      

  3.   

    在两次算起来语句执行中间是不是应该把 pstmt.close();pstmt = null;然后再执行第二句sql语句
      

  4.   

    要是在同一个事务中要设置conn.setAutoCommit(false);默认是自动提交,让后在catch块中加回滚等,
    PreparedStatement pstmt=null这里不设置初始值的话pstmt.close()应该会编译不过去,直接出错吧。
      

  5.   


    可是我认为根据executeUpdate()的字面意思,在第一句pstmt.executeUpdate();执行的时候,就已经执行前面准备好的一句pstmt=con.prepareStatement(sql)了啊,这时setAutoCommit(FALSE)还有意义么?我也知道,这里的PreparedStatement是可以改成我已经理解了的Statement的,所以,我认为要setAutoCommit(FALSE)产生作用,就只能用Statement的addBatch方法进行批处理,大家说说看,对么,
      

  6.   

    没有什么不好.! 当然如果你是增删改操作的话记得把Connection的自动提交设置为false,,  执行完了再提交