本文转载自:http://blog.sina.com.cn/s/blog_5ce9f5040100fe57.html
在一对多的关联操作中,通常在一方插入记录后,需要获取到当前记录的id,以方便进行多方的插入操作。要解决这一问题,在JDBC中至少有三种不同的实现方法:
1.在插入语句后添加一条查询,利用resultset来得到id号
psmt = con.prepareStatement
("insert into orders (receiver,address,telephone,total,detailnum,userid)values(?,?,?,?,?,?);select
@@identity");
psmt.setString(1, order.getReceiver());
……
results = psmt.executeQuery();
if(results.next())
{
num = results.getInt(1);
}
2.利用generatedKey来获取id
psmt = con.prepareStatement
("insert into orders (receiver,address,telephone,total,detailnum,userid)values
(?,?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
psmt.setString(1, order.getReceiver());
……
psmt.executeUpdate();
results = psmt.getGeneratedKeys();
int num = -1;
if(results.next())
{
num = results.getInt(1);
}
3.调用存储过程来实现,当然这种情况下,插入对象的属性不宜过多,否则存储过程的输入参数太多。在存储过程中,将id作为输出参数返回
CallableStatement proc = conn.prepareCall("{call proc_insert(?,?,?)}");
proc.setString(1, cardname);
proc.setInt(2, money);
proc.registerOutParameter(3, Types.INTEGER);
proc.execute();
num = proc.getInt(3)
@@identity");
psmt.setString(1, order.getReceiver());
……
results = psmt.executeQuery();
if(results.next())
{
num = results.getInt(1);
}
2.利用generatedKey来获取id
psmt = con.prepareStatement
("insert into orders (receiver,address,telephone,total,detailnum,userid)values
(?,?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
psmt.setString(1, order.getReceiver());
……
psmt.executeUpdate();
results = psmt.getGeneratedKeys();
int num = -1;
if(results.next())
{
num = results.getInt(1);
}
3.调用存储过程来实现,当然这种情况下,插入对象的属性不宜过多,否则存储过程的输入参数太多。在存储过程中,将id作为输出参数返回
CallableStatement proc = conn.prepareCall("{call proc_insert(?,?,?)}");
proc.setString(1, cardname);
proc.setInt(2, money);
proc.registerOutParameter(3, Types.INTEGER);
proc.execute();
num = proc.getInt(3)