代码是
ct.setAutoCommit(false);
ct.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
String sql = "insert into orders(usersId,totalPrice,orderDate) values(?,?,now())";
ps = ct.prepareStatement(sql);
ps.setInt(1, user.getId());
ps.setDouble(2, myCar.getTotalPrice());
ps.executeUpdate();

sql = "select LAST_INSERT_ID() from orders";
ps = ct.prepareStatement(sql);
rs = ps.executeQuery();
int ordersid = 0;
if(rs.next())
{
ordersid = rs.getInt(1);
}
ArrayList<Book> al = myCar.getBookCar();
for(int i=0;i<al.size();i++)
{
Book book = al.get(i);
sql = "insert into ordersiten(ordersId,bookId,bookNum) values(?,?,?)";
ps = ct.prepareStatement(sql);
ps.setInt(1, ordersid);
ps.setInt(2, book.getId());
ps.setInt(3, book.getBookNum());
ps.executeUpdate();
}
ct.commit();
orders 表的主键 和ordersiten的主键 都设置为自增长,在同一个事务中操作,会出现
java.sql.SQLException: Duplicate entry '0' for key 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2847)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1531)
at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1347)
at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:958)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1957)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1880)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1741)
错误,怎么解决啊

解决方案 »

  1.   

    insert into ordersiten(ordersId,bookId,bookNum) values(?,?,?)打印出来在客户端执行看看报什么错误
      

  2.   

    你用了spring 了吗,请说明你的具体环境,你用到了自动增长,那么就需要
    insert into orders(usersId,totalPrice,orderDate) values(?,?,now())
    而是这样写
    insert into orders(totalPrice,orderDate) values(?,now());然后在绑定之;
    同时如果用到了Srping 还需要相应的配置才能生效,生成方式应为assigned自动生成,否则会给你报空值异常,应用程序中并不知道你的数据库的自动增长机制。重要的是你需要你用的什么框架搭建的应用程序。