有时insert数据,数据ID为自动生成,需要获取ID。
以下就是获取ID的方法:
public static String insertByID(String sql,IDataBaseBean bean,ArrayList<Object> keyvalueList,ArrayList<Class<?>> classtypeList,SingleDataSource datasource) throws SQLException{
Connection conn = null;
try {
conn = datasource.getConnection();
//这里设置返回值
PreparedStatement ps = conn.prepareStatement(sql,new String[]{"ID"});
setPreparedValue(ps, keyvalueList, classtypeList);//设置preparedStatement值
ps.executeQuery();
ResultSet rs = ps.getGeneratedKeys();
if(rs!=null && rs.next())
{
return String.valueOf(rs.getInt(1));//返回主键值
}
} finally {
if(conn!=null)
conn.close();
}
return "";
}
标签:insert,jdbc,String,ps,rs,null,ID,conn From: https://blog.51cto.com/u_2465818/6209773