我需要将哈希值插入数据库.以下是我必须在table1列键和值中插入值的代码模板:
use DBI;
use strict;
%hash; #assuming it already contains desired values
my $dbh = DBI->connect(
"dbi:Sybase:server=$Srv;database=$Db",
"$user", "$passwd"
) or die sprintf 'could not connect to database %s', DBI->errstr;
my $query= "Insert INTO table1(key, values) VALUES (?,?) ";
my $sth = $dbh->prepare($query)
or die "could not prepare statement\n", $dbh->errstr;
$sth-> execute or die "could not execute", $sth->errstr;
Run Code Online (Sandbox Code Playgroud)
我知道如何使用数组插入值,即使用execute_array(),但不知道如何插入%hashtable1中存在的值.
有什么建议?
以下使用execute_array您问题中提到的功能.我测试了它.
my $dbh = DBI->connect("DBI:mysql:database=$DB;host=$host;port=$port", $user, $password);
my %hash = (
1 => 'A',
2 => 'B',
0 => 'C',
);
my @keys = keys %hash;
my @values = values %hash;
my $sth = $dbh->prepare("INSERT INTO table1(id, value) VALUES (?,?);");
$sth->execute_array({},\@keys, \@values);
Run Code Online (Sandbox Code Playgroud)
(对不起,我没有Sybase数据库可以使用,或者我以它为例.)