如何使用Perl的DBI模块将哈希值插入数据库? [英] How do I insert values from a hash into a database using Perl's DBI module?

查看:99
本文介绍了如何使用Perl的DBI模块将哈希值插入数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将哈希值插入数据库。以下是代码模板,我必须在table1列 key value 中插入值:

I need to insert values from a hash into a database. Following is the code template I have to insert values in table1 column key and value:

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; 

我知道如何使用数组插入值,即使用 execute_array(),但不知道如何插入表1中%hash 中的值。

I know how to insert values using array i.e use execute_array(), but do not know how to insert values present in %hash in table1.

任何建议?

推荐答案

以下内容使用了您的问题中提到的 execute_array 函数。我测试了

The following uses the execute_array function as mentioned in your question. I tested it.

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);

(对不起,我没有Sybase数据库,或者我会使用它例如。)

(Sorry, I don't have a Sybase database to work with, or I'd use it as an example.)

这篇关于如何使用Perl的DBI模块将哈希值插入数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆