在简单mysql查询(perl)中使用哈希值

在简单mysql查询(perl)中使用哈希值,mysql,perl,Mysql,Perl,有人能帮我找出正确的语法吗 for (my $i = 0; $i <=3; $i++) { $store = qq(INSERT INTO main (creator_name,relationship) VALUES("$data{creatorname}",$data{"relationship$i"}) ); 我现在使用的是一个日期,它看起来不像是一个占位符。正如@mob所说,你应该使用查询参数,而不是在如何将变量直接插入字符串中 $store = qq(INS

有人能帮我找出正确的语法吗

for (my $i = 0; $i <=3; $i++)
{

    $store = qq(INSERT INTO main (creator_name,relationship) 
    VALUES("$data{creatorname}",$data{"relationship$i"}) );

我现在使用的是一个日期,它看起来不像是一个占位符。

正如@mob所说,你应该使用查询参数,而不是在如何将变量直接插入字符串中

$store = qq(INSERT INTO main (creator_name, relationship) VALUES (?, ?));
$st = $dbi->prepare($store);
for (my $i = 0; $i < 3; $i++)
{
  $st->execute($data{creatorname}, $data{"relationship$i"});
}

运行此Perl脚本的输出表明插值是有效的。

正如mob和Bill所指出的,如果可能,最好使用占位符,但这不是代码不起作用的原因

它不起作用,因为您试图在一个字符串中执行两级变量插值:首先将$i插入“relationship$i”,然后将$data{“relationship$i”}插入qq引用的较大字符串中。它们不会那样筑巢

这将有助于:

for (my $i = 0; $i <=3; $i++)
{
    my $relationship = $data{"relationship$i"}
    $store = qq(INSERT INTO main (creator_name,relationship) 
    VALUES("$data{creatorname}",$relationship ) );

for(my$i=0;$i这对眼睛来说有点难,但是如果你总是有三行要输入,那么你可以在一个
execute()
中完成这一切:


my$sth=$dbh->prepare(指针#1:使用占位符谢谢你的回复,比尔。我之前没有显示另一个字段,因为它很复杂。“DATE\u ADD(NOW(),INTERVAL$INTERVAL)”,出于某种原因,它不允许我将其作为占位符值添加。您好。$store=qq(插入主(release\u DATE)值(DATE\u ADD)(NOW(),INTERVAL?);my$sth=$dbh->prepare($store);$sth->execute($INTERVAL)或die$dbh->errstr;结果是“您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以获得正确的语法使用方法”)知道为什么吗?啊-我忘了
INTERVAL
后面必须跟一个整数和一个增量。如
间隔3小时
间隔1年
。整数部分可以是参数。增量的关键字不能是参数。我已修复了上面的代码示例,将
HOUR
添加为间隔增量类型。想法不错,但双插值确实有效。请看我在回答中添加的示例。
$store = qq(INSERT INTO main (creator_name, relationship, complicated_column) 
    VALUES (?, ?, DATE_ADD(NOW(), INTERVAL ? HOUR)));
$st = $dbi->prepare($store);
for (my $i = 0; $i < 3; $i++)
{
  $st->execute($data{creatorname}, $data{"relationship$i"}, $interval);
}
$ cat test.pl
$i = 1;
$data{"key$i"} = "word";
$s = qq(string with parentheses ($data{"key$i"}));
print $s, "\n";

$ perl test.pl
string with parentheses (word)
for (my $i = 0; $i <=3; $i++)
{
    my $relationship = $data{"relationship$i"}
    $store = qq(INSERT INTO main (creator_name,relationship) 
    VALUES("$data{creatorname}",$relationship ) );
my $sth = $dbh->prepare(<<'__eosql');
          INSERT INTO main (time_column, creator_name, relationship)
          SELECT NOW() + INTERVAL ? HOUR, -- placeholder for $interval
                 ?,                       -- $data{creatorname}
                 relation
            FROM (SELECT ? AS relation    -- $data{relationship1}
                   UNION ALL
                  SELECT ?                -- $data{relationship2}
                   UNION ALL
                  SELECT ?) d             -- $data{relationship3}
          __eosql

$sth->execute($interval, @data{qw(creatorname relationship1 relationship2 relationship3)});