获取刚插入的主键
StringBuffer sql = new StringBuffer(" insert into tbe_paper(jointime,papername)values(?,?) ");
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs=null;
int result=0;
List<PaperModel> list=new ArrayList<PaperModel>();
PaperModel model=null;
try {
con = JdbcUtils.createInstance().getCon();
pstmt = con.prepareStatement(sql.toString(),Statement.RETURN_GENERATED_KEYS);
pstmt.setLong(1, System.currentTimeMillis());
pstmt.setString(2, "试卷");
pstmt.executeUpdate();
rs = pstmt.getGeneratedKeys();
if(rs.next()){
System.out.println(rs.getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.release(con, pstmt, rs);
}
第二个案例:
boolean b=false;
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
QuestionModel model=null;
int result=-1;
try {
conn=JdbcUtils.createInstance().getCon();
boolean autoCommit=conn.getAutoCommit();
//关闭自动提交功能
conn.setAutoCommit(false);
String sql="insert into t_paper(jointime,papername)values(?,?)";
st=conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
st.setLong(1,System.currentTimeMillis());
st.setString(2, paper.getPaperName());
st.executeUpdate();
rs=st.getGeneratedKeys();
if(rs.next()){
result=rs.getInt(1);
}else{
return b;
}
sql="insert into t_paper_questions(title,options,"
+ "answer,type,point,qid,paperid)values(?,?,?,?,?,?,?)";
st=conn.prepareStatement(sql);
for (int i = 0; i < questions.size(); i++) {
model=questions.get(i);
st.setString(1, model.getTitle());
st.setString(2, model.getOptions());
st.setString(3, model.getAnswer());
st.setString(4, model.getType());
st.setInt(5, model.getPoint());
st.setInt(6, i+1);
st.setInt(7, result);
st.addBatch();
}
int [] arr=st.executeBatch();
if(arr==null || arr.length==0){
return b;
}
//提交事务
conn.commit();
b=true;
//恢复原来的提交模式
conn.setAutoCommit(autoCommit);
} catch (SQLException e) {
System.out.println("操作失败!!!任务撤销!!!");
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
JdbcUtils.release(conn, st, rs);
}
return b;