I am inserting data from perl in my sqlite database.
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.
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
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.
Also, you should explicitly name the columns in the INSERT statement:
INSERT INTO Table (Col1, Col2) VALUES (Val1, Val2)
精彩评论