Perl dbi prepare is putting wrong quote

旧巷老猫 提交于 2019-12-24 12:26:05

问题


My code is similar to the below:

$sth = $dbh->prepare("CREATE TABLE IF NOT EXISTS ? (`id` bigint(100) unsigned NOT NULL AUTO_INCREMENT");
$sth->execute('test');

I end up with the error:

ERROR 1064 (42000): 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 ''test'

From the trace I found perl DBI put single quote around the table name, which mysql doesnt like. How to tell DBI not to put any quote or to put (`) instead of single quote?


回答1:


It's just doing what you asked. When given a string, ? is equivalent to a string literal. So

SELECT * FROM Table WHERE field = ?

means

SELECT * FROM Table WHERE field = 'test'

and

SELECT * FROM ?

means

SELECT * FROM 'test'

You need to use

$dbh->prepare("
   CREATE TABLE IF NOT EXISTS ".( $dbh->quote_identifier('test') )." (
             `id` bigint(100) unsigned NOT NULL AUTO_INCREMENT
          )
");



回答2:


You can not use a placeholder for a table or column name. PreparedStatement will interpret this value as a string and make sinlge quotes around it.



来源:https://stackoverflow.com/questions/32177656/perl-dbi-prepare-is-putting-wrong-quote

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!