使用PreparedStatement在执行添加语句后,获得生成的主键值

字体大小: 中小 标准 ->行高大小: 标准
public int getInsert(String sql , List parms){
int count = 0 ;
ResultSet rs = null;
try {
PreparedStatement  preparedStatement = this.connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
for(int i = 0 ; i < parms.size() ; i++){
if(parms.get(i).getClass().getCanonicalName().equals("java.lang.Integer"))
{
preparedStatement.setInt(i+1, Integer.parseInt(parms.get(i).toString()));
}else if(parms.get(i).getClass().getCanonicalName().equals("java.lang.Float")){

preparedStatement.setFloat(i+1, Float.parseFloat(parms.get(i).toString()));

}else{
preparedStatement.setString(i+1, parms.get(i).toString());
}
}
preparedStatement.executeUpdate();

this.connection.commit();
rs = preparedStatement.getGeneratedKeys();//在这里
while(rs.next()){
count = rs.getInt(1);//在这里
}
System.out.println(count+"主键");
} catch (SQLException e) {
try {
this.connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
return 0 ;
}
return count ;
}

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/68181.html