[英]mysqlite, inserting data and special character cases in perl
I am inserting data from perl in my sqlite database. 我在我的sqlite数据库中从perl插入数据。
here is my coding: 这是我的编码:
how do i make this case work if my values have special characters like quotes? 如果我的值具有引号等特殊字符,如何使这种情况起作用?
sub ADDROWDATATODATABASE
{
my $dbh1 = $_[0];
my $table = $_[1];
my @DATA = @{$_[2]};
my $string = ();
foreach (@DATA) { $string .= "'$_',"; } $string =~ s/,$//;
$dbh1->do(qq|insert into $table values(NULL,$string);|);
my $date = `date`;
print "[MYSQLITE_ADDROW.pl] $date : ADDING DATA INTO DATABASE <p>";
}
Use placeholders and bind values . 使用占位符并绑定值 。 This will keep your program safer from SQL injection, too. 这也将使您的程序免受SQL注入的侵害。
my $statement = $dbh->prepare("insert into $table VALUES(NULL, ?,?,?,?)");
$statement->execute(@DATA);
Assuming that the number of elements in @DATA
is only known at runtime (and that it is the correct number of elements for $table
), you can use 假设@DATA
的元素数仅在运行时才知道(并且它是$table
的正确元素数),可以使用
my $statement = $dbh->prepare("insert into $table VALUES(NULL" . ",?"x@DATA . ")";
$statement->execute(@DATA);
to make sure that the statement has the right number of placeholders. 确保该语句具有正确的占位符数量。
You need to call a function to "escape" the values. 您需要调用一个函数以“转义”值。 How you do that depends on what database you're actually using — MySQL and SQLite are different products. 如何执行取决于您实际使用的数据库-MySQL和SQLite是不同的产品。
Also, you should explicitly name the columns in the INSERT statement: 另外,您应该在INSERT语句中显式命名列:
INSERT INTO Table (Col1, Col2) VALUES (Val1, Val2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.