我的MySQL查询由于引号或缺少引号而无法正常工作,但我不了解如何正确使用它。我需要一些解释:
写入.csv文件的Perl脚本:
open(ECRIRE,">$ARGV[1]") || die ("Impossible de creer le fichier de sortie");
foreach my $key (sort keys %caisse)
{
print ECRIRE "insert into etablissement(code_etablissement,nom, contact_ce_nom, contact_ce_tel, contact_ce_mail) values ($key,$caisse{$key}[0];$caisse{$key}[1];$caisse{$key}[2];$caisse{$key}[3]) on duplicate key update contact_ce_nom=$caisse{$key}[1],contact_ce_tel=$caisse{$key}[2],contact_ce_mail=$caisse{$key}[3];\n";
}
close(ECRIRE);
执行SQL请求的Bash脚本:
$mysql -f -h $db_address -P $db_port -u $db_user -p$db_passwd $db_name < $vtiger_temporary_file_etablissement_clean
Mysql正在为几乎所有类似的信息而哭泣
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'migrationrh2cepal@mail.com) on duplicate key update contact_ce_no' at line 1
我甚至尝试用单引号引用每个变量,结果相同......
编辑:使用DBI for perl
现在代码如下:
foreach my $key (sort keys %caisse)
{
my $insert = $sql_connection->prepare('insert into etablissement values(?, ?, ?, ?, ?, ?) on duplicate key update');
$insert->execute($key, $caisse{$key}[0], $caisse{$key}[1], $caisse{$key}[2], $caisse{$key}[3],'');
}
我现在有#34;重复键&#34;问题。如何在重复键上添加&#34;&#34;声明在这里? 我试着在最后添加它,就像这样:
my $insert = $sql_connection->prepare('insert into etablissement values(?, ?, ?, ?, ?, ?) on duplicate key update');
但它不能正常工作
答案 0 :(得分:4)
不要自己引用变量,而是使用DBI模块和占位符:
$db = 'DBI'->connect(...);
my $insert = $db->prepare('insert into etablissement values(?, ?, ?)');
$insert->execute($key, $caisse{$key}[0], $caisse{$key}[1]);
对于重复值,通常使用编号占位符:
my $insert = $db->prepare(<<'__SQL__');
INSERT INTO etablissement
(code_etablissement, nom, contact_ce_nom, contact_ce_tel, contact_ce_mail)
VALUES (:1, :2, :3, :4, :5)
ON DUPLICATE KEY UPDATE contact_ce_nom = :3,
contact_ce_tel = :4,
contact_ce_mail = :5'
__SQL__
$insert->execute($key, @{ $caisse{$key} }[0 .. 3]);
如果您的驱动程序不支持它们(我在DBD::mysql中没有看到它们),您可以解决它,例如
my $insert = $db->prepare(<<'__SQL__');
INSERT INTO etablissement
(code_etablissement, nom, contact_ce_nom, contact_ce_tel, contact_ce_mail)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE contact_ce_nom = ?,
contact_ce_tel = ?,
contact_ce_mail = ?
__SQL__
$insert->execute($key, @{ $caisse{$key} }[0 .. 3], @{ $caisse{$key} }[1 .. 3]);
或者您可以使用quote
并完全省略占位符。
答案 1 :(得分:0)
使用choroba的部分答案:
最后一个问题是&#34;如何在perl DBI上使用重复键语法?&#34;
喜欢这个
my $insert = $sql_connection->prepare('insert into etablissement values(?, ?, ?, ?, ?, ?) on duplicate key update contact_ce_nom=?,contact_ce_tel=?,contact_ce_mail=?');
$insert->execute($key, $caisse{$key}[0], $caisse{$key}[1], $caisse{$key}[2], $caisse{$key}[3],'',$caisse{$key}[1],$caisse{$key}[2],$caisse{$key}[3]);
最后3个ARGS由&#34; on udplicate key&#34;语法...