我有几个数据文件,如下列: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。 –