JDBC插入数据库获得主键的方式,目前我总结出两种
1.适用于自动增长列的数据库(如sql-server,mysql)
/**
* 插入数据获得主键
* @param annex
* @return
*/
public long save2(Annex annex){
long annexId = 0;
//获得连接
Connection con = ProxoolManager.getConnection();
String insertSQL = "insert into annex values (?,?,sysdate,?,?,?)";
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
pstmt = con.prepareStatement(insertSQL,Statement.RETURN_GENERATED_KEYS) ;
pstmt.setInt(1, 1);
pstmt.setString(2, annex.getAnnexName());
pstmt.setString(3, annex.getAnnexFormat());
pstmt.setString(4, DefineUtil.getFilePath()+File.separator+annex.getFileName()+"."+annex.getAnnexFormat());
pstmt.setInt(5, 1);
//将数据保存到数据库
pstmt.executeUpdate();
//获得主键
rs=pstmt.getGeneratedKeys();
if(rs.next()){
System.out.println(rs.getString(1));
annexId = rs.getLong(1);
}
}catch(SQLException ex){
ex.printStackTrace();
}
return annexId;
}
如果用ORACLE数据库使用上所述方法,获得的将是ROW_ID,并不是我们真正想要的主键值
2.适合Oracle数据库的方法
/**
* 插入数据获得主键
* @param annex
* @return
*/
public long save3(Annex annex){
long annexId = 0;
//获得连接
Connection con = ProxoolManager.getConnection();
String insertSQL = "BEGIN insert into annex (ANNEX_NAME,ANNEX_CREATTIME,ANNEX_FORMAT,ANNEX_PATH,ADVUSER_ID) values (?,sysdate,?,?,?) returning ANNEX_ID into ?; END;";
try {
CallableStatement call = con.prepareCall(insertSQL);
call.setString(1, annex.getAnnexName());
call.setString(2, annex.getAnnexFormat());
call.setString(3, DefineUtil.getFilePath()+File.separator+annex.getFileName()+"."+annex.getAnnexFormat());
call.setInt(4, 1);
call.registerOutParameter(5, OracleTypes.NUMBER);
call.execute();
annexId = call.getInt(5);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return annexId;
}
CallableStatement 主要用来执行存储过程,可获得存储过程的输出值
既然是存储过程,SQL语句中,一定不能缺少BEGIN END,(一定不能少)
call.registerOutParameter(5, OracleTypes.NUMBER); 设置输出标引位置,以及输出类型