使用Zend_Db在varbinary(SQL Server)字段中插入blob(来自mysql)数据

时间:2012-03-01 12:45:35

标签: sql-server-2008 pdo blob zend-db varbinary

我有一个需要与SQL Server表同步的MySQL表。所以来自MySQL的数据移动到SQL Server。它由简单的SELECT *和INSERT INTO查询完成。但是,我遇到了将一些BLOB数据迁移到varbinary字段的问题。

所以我有这段代码:

$db_mysql = new Zend_Db_Adapter_Pdo_Mysql(array(
    'host'      =>  '127.0.0.1',
    'username'  =>  '<user>',
    'password'  =>  '<password>',
    'dbname'    =>  '<db>',
    'charset'   =>  'utf8'
));
$db_mssql = new Zend_Db_Adapter_Pdo_Mssql(array(
    'pdoType'   =>  'sqlsrv',
    'host'      =>  '<host>',
    'username'  =>  '<user>',
    'password'  =>  '<password>',
    'dbname'    =>  '<db>'
));

$rows = $db_mysql->fetchAll("SELECT Id, Picture FROM Rosters");
foreach ($rows as $row) {
    $update_sql = "UPDATE Rosters SET Picture = :picture WHERE Id = :id";

    $stmt = new Zend_Db_Statement_Pdo($db_mssql, $update_sql);
    $stmt->bindValue(":picture", bin2hex($row['Picture']), Zend_Db::PARAM_LOB);
    $stmt->bindValue(":id", $row['Id'], Zend_Db::PARAM_INT);

    try {
        $stmt->execute();
    } catch (Exception $e) {
        echo $e->getMessage();
        var_dump($e);
        die();
    }
}

这给了我一个令人难以置信的不太有用的错误消息:PDOException: SQLSTATE[HY000]: General error: 257 General SQL Server error: Check messages from the SQL Server [257] (severity 16) [(null)]

MySQL Blob字段定义为BLOB,属性为BINARY,SQL Server字段定义为(varbinary(max), null)。我认为这只是一个简单的错误,但我无法弄清楚。任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

确定。我自己发现了,这是工作代码:

$db_mysql = new Zend_Db_Adapter_Pdo_Mysql(array(
    'host'      =>  '127.0.0.1',
    'username'  =>  '<user>',
    'password'  =>  '<pass>',
    'dbname'    =>  '<db>',
    'charset'   =>  'utf8'
));
$db_mssql = new Zend_Db_Adapter_Pdo_Mssql(array(
    'pdoType'   =>  'odbc',
    'host'      =>  '<host>',
    'username'  =>  '<user>',
    'password'  =>  '<pwd>',
    'dbname'    =>  'Roosters'
));
    $rows = $db_mysql->fetchAll("SELECT Id, Picture FROM Rosters");
    foreach ($rows as $row) {
        $update_sql = "UPDATE Rosters SET Picture = CONVERT(varbinary(max), :picture, 2) WHERE Id = :id";
        $stmt = new Zend_Db_Statement_Pdo($db_mssql, $update_sql);
        $stmt->bindValue(":picture", bin2hex($row['Picture']));
        $stmt->bindValue(":id", $row['Id'], Zend_Db::PARAM_INT);

    try {
        $stmt->execute();
    } catch (Exception $e) {
        echo $e->getMessage();
        var_dump($e);
        die();
    }
}
?>