有沒有更簡單的方法將char添加到perl中數組元素的開頭和結尾。將char添加到數組元素
Ex:my $str ='table1,table2,table3'
my @arry = split (/,/,$str)
我喜歡的輸出應該看起來像
'table1','table2','table3'
因此,它可以在SQL查詢中使用
感謝。
有沒有更簡單的方法將char添加到perl中數組元素的開頭和結尾。將char添加到數組元素
Ex:my $str ='table1,table2,table3'
my @arry = split (/,/,$str)
我喜歡的輸出應該看起來像
'table1','table2','table3'
因此,它可以在SQL查詢中使用
感謝。
join(',', map "'$_'", @arry)
是你要求的。
但是,更好的做法是使用佔位符:
my $str = 'table1,table2,table3';
my @arry = split(/,/, $str);
if (@arry) {
my $query = 'select * from tablename where colname in (' . join(',',('?') x @arry) . ')';
my $sth = $dbh->prepare($query);
$sth->execute(@arry);
...
}
如果你要使用DBI(https://metacpan.org/module/DBI)與數據庫進行工作,如果你在查詢中使用佔位符它可以爲你做,所以你不必引用值。
例如,如果要插入的東西到表:
$dbh->do("INSERT INTO table VALUES(?, ?, ?)", undef, @arry)
or die $dbh->errstr;
其中@arry
恰好含有3個值的陣列,以被插入到表中。
更多關於這個可以在這裏找到https://metacpan.org/module/DBI#Placeholders-and-Bind-Values
非常感謝。按照您的建議使用佔位符。 – Sourcecode
只是注意空數組......不幸的是,'()中的colname不是有效的SQL – ysth