我有幾個數據文件,如下列:PHP PDO TRY。處理重複
- table 1 - table 2 - table 3
id val id val id val
============ ========== ===========
1 one 1 uno 1 un
2 two 4 dos 6 deux
3 three 5 tres 7 trois
我試圖將其插入到數據庫中期待:
= result table
id val
============
1 one
2 two
3 three
d1 uno
4 dos
5 tres
dd1 un
6 deux
7 trois
數據庫結構是:
= sqlite database file: data.db
CREATE TABLE register (
id VARCHAR(3) PRIMARY KEY,
val VARCHAR(16)
);
我想出了這種解決方案:
<?php
$table1 = array("1"=>"one","2"=>"two","3"=>"three");
$table2 = array("1"=>"uno","4"=>"dos","5"=>"tres");
$table3 = array("1"=>"un","6"=>"deux","7"=>"trois");
$fileHandle = new PDO("sqlite:data.db");
$fileHandle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach($table1 as $key => $value){
try{
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('".$key."', '".$value."');");
}catch(PDOException $e){
if($e->getCode()=='23000'){ // if key exists, add a "d" to differentiate
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('d".$key."', '".$value."');");
}
}
}
// keys: 1, 2, 3
foreach($table2 as $key => $value){
try{
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('".$key."','".$value."');");
}catch(PDOException $e){
if($e->getCode()=='23000'){ // if key exists, add a "d" to differentiate
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('d".$key."', '".$value."');");
}
}
}
// keys: 1, 2, 3, d1, 4, 5
foreach($table3 as $key => $value){
try{
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('".$key."', '".$value."');");
}catch(PDOException $e){
echo " getCode : ".$e->getMessage()."\n";
if($e->getCode()=='23000'){ // if key exists, add a "d" to differentiate
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('d".$key."', '".$value."');");
}
}
}
// Signals error on the INSERT in the CATCH body
?>
但卡在第二次出現的關鍵。在示例中生成重複鍵(d1)。
SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: register.id
我可以看到重複模式,但我看不出如何濃縮它。或者重新修改修改後的密鑰。
在此先感謝您的意見。
試圖集中我的問題。沒有一個結構可以改變;數據和數據庫已經存在(有數千條記錄)。目標是通過添加一個改變它們來插入重複的ID(約束阻止)。因此,如果我們有,爲了爭論,有三個記錄與他們相同的ID 1,1,1,他們將插入數據庫爲1,D1,DD1。 –