简体   繁体   English

如何将Perl变量插入Sqlite3

[英]How to insert Perl variables into Sqlite3

I want to insert values into Sqlite3 table using Perl DBI. 我想使用Perl DBI将值插入Sqlite3表。 I was able to insert hard coded values without any problem. 我能够毫无问题地插入硬编码值。 When I tried to use perl variables, then I get an error "DBD::SQLite::db do failed: no such column:" 当我尝试使用perl变量时,出现错误“ DBD :: SQLite :: db失败:没有这样的列:”

This works: 这有效:

$dbh->do("insert into Gene values (12, 'AAAAAA', 66, 86, 76)");

But this code 但是这段代码

$dbh->do("INSERT INTO Gene values (NULL, $sequence, $siteNumber, $begin, $length)");

throws the error 引发错误

DBD::SQLite::db do failed: no such column

You should always prepare and execute your SQL statements and use placeholders for variable values as a matter of course. 当然,您应该始终prepareexecute SQL语句,并对变量值使用占位符。

Try this code 试试这个代码

my $sth = $dbh->prepare('INSERT INTO Gene VALUES (?, ?, ?, ?, ?)');
$sth->execute(undef, $sequence, $siteNumber, $begin, $length);

Your problem will have been at $sequence, which required quoting to be a valid SQL string literal in the insert statement. 您的问题将出在$ sequence上,这需要在insert语句中引用有效的SQL字符串文字。 As a result it thought you were trying to refer to a column called AAAAAA, and not the string 'AAAAAA' that you intended. 结果,它以为您尝试引用的是称为AAAAAA的列,而不是您想要的字符串“ AAAAAA”。 Perl's string interpolation doesn't add the quotes for you. Perl的字符串内插不会为您添加引号。

Placeholders and $dbh->prepapre are by far the most robust solution here though (for example, what to do if your string contains the quote character ' ? $dbh->prepare already has that coded correctly). 占位符和$ dbh-> prepapre是到目前为止最可靠的解决方案(例如,如果您的字符串包含引号''$ dbh-> prepare已经正确编码了,该怎么办)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM