我试图在pSQL表中插入一行,将键和值都指定为占位符:
my @keys = keys %db_entr;
my @vals = values %db_entr;
my @items = (@keys, @values);
my $dbh = DBI->connect("DBI:Pg:dbname=testdb;host=localhost", "username", 'password', {'RaiseError' => 1});
my $sth = $dbh->prepare("INSERT INTO grid ( ?, ?, ? ) values ( ?, ?, ? )");
my $rows = $sth->execute(@items);
print "$rows effected\n";
然而,无论我做什么,这都给了我一个错误:
DBD::Pg::st execute failed: ERROR: syntax error at or near "$1"
LINE 1: INSERT INTO grid ( $1, $2, ...
^ at ./file.pl line 262, <STDIN> line 11.
有没有人知道我可能做错了什么?
答案 0 :(得分:6)
您不能对这些列名使用占位符:
INSERT INTO grid (?, ?, ?) VALUES (?, ?, ?)
您必须明确指定列名称,并且只能使用占位符作为值:
INSERT INTO grid (x, y, z) VALUES (?, ?, ?)
答案 1 :(得分:4)
您无法在prepare
调用中使用占位符作为列名。您可以做的最好的事情是将变量名称插入到SQL字符串中,或者使用sprintf
来执行等效操作。
这是一个例子,但您可能需要做一些不同的事情。请注意,它会修改@items
数组,每次prepare
的内容可能已更改时,您需要再次调用@items
。
my $sth = $dbh->prepare(
sprintf "INSERT INTO grid ( %s, %s, %s ) values ( ?, ?, ? )",
splice @items, 0, 3
);
my $rows = $sth->execute(@items);
print "$rows affected\n";