oracle中返回主键值

在今天的ATM中,就用纯粹的jdbc来处理数据,当发现用user ,card,log之间的关系,在save用户之后,要用到user中id来关联到card中,的字段,而oracle中插入和跟新之后是返回的插入和更新的行数,后来想了想,也上网搜了一些资料,现在总结如下,

/**
* 添加用户
*/
@Override
public int save(User user)
{
temp = -1;
final String sql = "insert into atm_user(username,password,sex,idCard) values(?,?,?,?)";

try
{
String key[] =
{ "id" };
ps = this.conn.prepareStatement(sql, key);
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.setString(3, String.valueOf(user.getSex()));
ps.setString(4, user.getIdCard());
temp = ps.executeUpdate();
System.out.println(temp);

rs = ps.getGeneratedKeys();
rs.next();
if (temp > 0)
{
temp = Integer.valueOf(rs.getString(1));
}

} catch (SQLException e)
{
e.printStackTrace();
try
{
conn.rollback();
} catch (SQLException e1)
{
e1.printStackTrace();
}
} finally
{
close();
}
return temp;
}

你可能感兴趣的:(oracle)