我正在尝试制作一个PHP代码,使我可以比较和同步SQL Server和MySQL中两个相同表之间的差异。这样就可以了,因此我只需要手动更新其中之一即可。但是,它不仅尝试插入差异,还尝试插入从SQL Server(主服务器)到MySQL(子服务器)的所有内容,并将内容加倍。这是代码:
<?php
$serverName = "<servername>";
$connectionInfo_mssql = array("Database"=>"<dbname>", "CharacterSet"=>"UTF-8");
try
{
$conn_mssql = new PDO("sqlsrv:Server=$serverName;Database=<dbname>");
$conn_mssql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn_mysql = new PDO("mysql:host=localhost;dbname=<dbname>", "<username>", "<password>");
$conn_mysql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$mssql_array = array();
$mssql_query = $conn_mssql->prepare("SELECT * FROM SALARY");
$mssql_query->execute();
while ($row = $mssql_query->fetch(PDO::FETCH_BOTH))
{
$mssql_array[] = array('SGRADE' => $row['SGRADE'], 'STEP' => $row['STEP'], 'AMOUNT' => $row['AMOUNT'], 'REMARK' => $row['REMARK'], 'uniquee' => $row['uniquee']);
}
foreach ($mssql_array as $key => $value)
{
$mysql_query = $conn_mysql->prepare("SELECT * FROM SALARY WHERE SGRADE = :SGRADE AND STEP = :STEP AND AMOUNT = :AMOUNT AND REMARK = :REMARK AND uniquee = :uniquee");
$mysql_query->bindParam(':SGRADE', $value['SGRADE'], PDO::PARAM_INT);
$mysql_query->bindParam(':STEP', $value['STEP'], PDO::PARAM_INT);
$mysql_query->bindParam(':AMOUNT', $value['AMOUNT'], PDO::PARAM_INT);
$mysql_query->bindParam(':REMARK', $value['REMARK'], PDO::PARAM_INT);
$mysql_query->bindParam(':uniquee', $value['uniquee'], PDO::PARAM_INT);
$mysql_query->execute();
if ($mysql_query)
{
$mysql_insert = $conn_mysql->prepare("INSERT INTO SALARY VALUES (:SGRADE, :STEP, :AMOUNT, :REMARK, :uniquee)");
$mysql_insert->bindParam(':SGRADE', $value['SGRADE'], PDO::PARAM_INT);
$mysql_insert->bindParam(':STEP', $value['STEP'], PDO::PARAM_INT);
$mysql_insert->bindParam(':AMOUNT', $value['AMOUNT'], PDO::PARAM_INT);
$mysql_insert->bindParam(':REMARK', $value['REMARK'], PDO::PARAM_INT);
$mysql_insert->bindParam(':uniquee', $value['uniquee'], PDO::PARAM_INT);
$mysql_insert->execute();
echo "Success";
}
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
此代码的工作方式是:选择SQL Server“ SALARY”表的所有内容,然后选择MySQL“ SALARY”表中的所有内容,然后仅插入差异。但是,它改为将所有内容插入子表中,从而将内容加倍。由于我将“唯一”列设置为PRIMARY KEY并自动递增,因此不允许这种情况发生,而是向我发送错误消息“错误:SQLSTATE [23000]:违反完整性约束:1062重复输入项“ 1” 'PRIMARY'“。关于如何使它起作用的任何想法吗?我做了一个类似的代码,而不是从两个表中选择所有内容,而是截断了子表并从主表中插入了所有内容,这很完美,但是我不喜欢这种方法因为处理数百个数据时它变得非常慢。关于如何使上面的代码工作的任何想法?