0

我正在通过循环进行插入,不幸的是,它似乎只插入了一些数据而忽略了一些。

我正在读取文件的内容并使用 PHP 将它们插入到 postgres 数据库中。

请参阅下面的代码。

$source='/Users/gsarfo/AVEC_ETL/TCCDec052016OSU.DAT';

$lines=file($source);

$len =sizeof($lines);

$connec = new PDO("pgsql:host=$dbhost;dbname=$dbname", $dbuser,    $dbpwd); 

$ins=$connec->query('truncate table tbl_naaccr_staging');

try {

    for ($x = 0; $x < $len; $x++) {
        $a1=substr($lines[$x],146,9);
        $a2=substr($lines[$x],2182,9);
        $a3=substr($lines[$x],192,3);
        $connec->beginTransaction();

        $sql2=$connec->prepare("INSERT INTO tbl_naaccr_staging
                                (addr,name, email) VALUES (?, ?, ?"); 

        $sql2->execute(array($a1,   $a2,    $a3));
        $connec->commit();     
    }
    $res=$connec->query($sql) ;
}

catch (PDOException $e) { 
    echo "Error : " . $e->getMessage() . "<br/>"; 
    die(); 
} 

if ($sql2)
{echo 'success';}
?>
4

2 回答 2

1

我不明白那将如何插入任何东西!

此行不正确

$sql2=$connec->prepare("INSERT INTO tbl_naaccr_staging
                       (addr,name, email) VALUES (?, ?, ?"); 
                                                         ^ ^ here

改正为

$sql2=$connec->prepare("INSERT INTO tbl_naaccr_staging
                       (addr,name, email) VALUES (?, ?, ?)"); 

此外,您的事务没有多大意义,因为它会提交每次更新,如果您没有启动事务就会发生这种情况。所以也许这会是明智的,并且会实现全有或全无的情况

此外,prepare 可以多次重复使用,因此也可以将其移出循环,您会发现您的脚本运行得也更快。

try {

    $connec->beginTransaction();   

    // move this out of the loop
    $sql2=$connec->prepare("INSERT INTO tbl_naaccr_staging
                            (addr,name, email) VALUES (?, ?, ?)");  

    for ($x = 0; $x < $len; $x++) {
        $a1=substr($lines[$x],146,9);
        $a2=substr($lines[$x],2182,9);
        $a3=substr($lines[$x],192,3);

        $sql2->execute(array($a1,   $a2,    $a3));
    }
    $connec->commit();  

    // I do not see a `$sql` variable so this query seems to have no function
    //$res=$connec->query($sql) ;
}

catch (PDOException $e) { 
    $connec->rollback();     

    echo "Error : " . $e->getMessage() . "<br/>"; 
    die(); 
} 
于 2016-12-13T18:54:33.527 回答
0

它起作用了,问题是由于插入的字符串中没有转义字符,所以 pg_escape_string 在插入之前帮助清除了字符串

于 2016-12-19T21:24:08.250 回答