在进行业务处理时,经常会遇到获取关联表的主键作为该表的外键的操作,在mybatis中这个操作已经封装好了,那么JDBC是如何进行操作的呢?我们查看JDBC的API后发现,其实JDBC的Statement接口和PreparedStatement已经进行了封装。
pst=connection.prepareStatement("",Statement.RETURN_GENERATED_KEYS);
参考代码:
try {
pst= connection.prepareStatement("insert into t_log(logMess,logTime) values(?,now())", 1);
//pst=connection.prepareStatement("",Statement.RETURN_GENERATED_KEYS);
pst.setObject(1,"哈哈测试自增");
int m=pst.executeUpdate();
rs= pst.getGeneratedKeys();
if(rs.next()){
System.out.println(rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
输出结果:



