Scenerio:
name
列unique
,因此当相同值到达时,插入不会更改表格INSERT INTO IGNORE
来防止迭代在事件发生时中断INSERT_IGNORE
发生时我得到0 如何解决此问题?
Connection con = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
con.setAutoCommit(false);
Statement s1 = (Statement) con.createStatement();
s1.executeUpdate("INSERT IGNORE INTO ORIGIN (ORI_NAME) VALUES(\""
+ d.getOriginName() + "\")");
Statement s2 = (Statement) con.createStatement();
s2.executeUpdate("INSERT IGNORE INTO STOCK (ORI_ID,S_TITLE) VALUES ("
+ "(SELECT ORI_ID FROM ORIGIN WHERE ORI_ID =LAST_INSERT_ID()),\""
+ d.getStockTitle() + "\")");
}
con.commit();
}
catch (Exception e)
{
if (con != null)
try
{
con.rollback();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
e.printStackTrace();
}
finally
{
if (con != null)
try
{
con.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
要插入数据库的CSV文件示例
US, P1, M, 200, 344
US, P1, L, 233, 344
US, P2, M, 444, 556
MX, Q4, L, 656, 777
答案 0 :(得分:5)
您熟悉MySQL的ON DUPLICATE KEY UPDATE
语法吗?
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
// Results are the same as doing an update.
// Note the way the PK can be used to avoid an IGNORE.
s1.executeUpdate("INSERT INTO ORIGIN (ORI_NAME) VALUES(\""
+ d.getOriginName() + "\" ON DUPLICATE KEY UPDATE ORI_ID=ORI_ID)");
此处涉及维护网站的失败电子邮件地址的实际示例:
http://blog.developpez.com/james-poulson/p10016/sql/ne-rien-modifier-en-cas-de-duplicate-key/
至于检索最后插入的id,以下内容来自上面的mysql.com链接:
Suppose that id is the AUTO_INCREMENT column. To make LAST_INSERT_ID() meaningful for updates, insert rows as follows:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3;
答案 1 :(得分:2)
如果要获取后续插入的ID,则代码必须测试LAST_INSERT_ID的0值,如果得到它,请在表上执行SELECT以找到插入的FK的正确值。
在伪代码中,这看起来像:
$err = mysql("insert ignore into mytable values ($x, $y)")
if($err){
do something for an error
}
$id = mysql("select last_insert_id()");
if($id == 0){
$id = mysql("select id from othertable where condition is true for the record I want to reference in my insert");
if($id == 0){
do something for error
}
}
mysql("insert into othertable VALUES ($id, other stuff)")
您必须将其翻译成您自己的应用程序和语言。