我正在尝试执行一个脚本来更新数据库:
my $sql_hash_update = 'UPDATE user SET hash = $hash , updated = 1 WHERE id = $row[0]';
my $sth_hash_update = $dbh->prepare($sql_hash_update);
$sth_hash_update->execute();
我得到的错误是这不是正确的语法,但这适用于 SQL 本身。
DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[0]' at line 1 at conexion.pl line 32.
知道我做错了什么吗?
最佳答案
你用的是单引号,所以这条语句
my $sql_hash_update = 'UPDATE user SET hash = $hash , updated = 1 WHERE id = $row[0]'
不会将 $hash
和 $row[0]
的值插入到 SQL 语句中。相反,它们将保持原样,因此该语句不是有效的 SQL
您可以简单地切换到双引号,它会插入,但最好像这样使用占位符
my $sql_hash_update = 'UPDATE user SET hash = ?, updated = ? WHERE id = ?';
my $sth_hash_update = $dbh->prepare($sql_hash_update);
$sth_hash_update->execute( $hash, 1, $row[0] );
这样你就避免了代码注入(inject)的风险,而且你只需要为许多不同的执行
调用准备
一次
只要 SQL 语法中允许使用表达式,占位符就有效。这意味着,例如,您不能为表名提供占位符,因为您不能在普通 SQL 语句中将表达式放在那里
关于mysql - SQL 语句在 Perl 下失败,但可以从命令行运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42392153/