我有一个运行 2 个线程的程序,每个线程都有自己的数据库 JDBC 连接,它们将访问/修改同一个数据库表 A,如下所示。表A只有2列(id,name),主键是id和name的组合。
statement stmt;
// first delete it if the record has exist in table
stmt.addBatch("delete from A where id='arg_id' and name='arg_name';");
// then insert it to table
stmt.addBatch("insert into A values (arg_id, arg_name);");
stmt.executeBatch();
2个线程可能会向表中插入相同的数据,我得到以下异常,
java.sql.BatchUpdateException: Duplicate entry '0001-joey' for key 1
at com.mysql.jdbc.Statement.executeBatch(Statement.java:708)
at com.mchange.v2.c3p0.impl.NewProxyStatement.executeBatch(NewProxyStatement.java:743)
at proc.Worker.norD(NW.java:450)
你知道我该如何解决这个问题吗?谢谢你。
问候,乔伊