Perl插入MySQL DB [英] Perl inserting into MySQL DB

查看:54
本文介绍了Perl插入MySQL DB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所拥有的:

  • MySQL数据库
  • 具有9列的表.
  • 使用需要插入表中的值生成的数组.

注意:自动生成的数组每次都有不同的长度,但是长度不会超过表中的列数.

Note: The array that gets generated automatically will have a different length every time but the length will not exceed the number of columns that I have in the table.

列名将类似于field1,field2,field3等,其中名称将始终以单词field开头,然后是数字.

The column names will be something like field1, field2, field3 etc. where the name will always being with the word field and then followed by a number.

我认为可以使用Perl的 map 函数来完成此操作,但是我对使用此功能不太满意,需要一些指导.

I think this can be done using Perl's map function but I'm not that good with using this function and need some guidance.

我想做这样的事情:

while ( (@Row) = $sql_stmt_h->fetchrow_array() ) {
 my $sql="
     INSERT INTO tablename (field$x) 
     VALUES (map function here ... which also needs to increment the $x in field$x so that it moves onto the next column name which would be field2 if we put the first value in field1. )";
}

推荐答案

创建您的Insert语句,以使用?占位符为数据插入所有字段.

Create your Insert statement to insert to all fields using ? placeholders for the data.

my $sql="
 INSERT INTO tablename (field1 field2 field3 field4 field5 field6 field7 field8 field9 ) 
 VALUES (? ? ? ? ? ? ? ? ?)";
my $insert_sth = $dbh->prepare($sql);

然后做类似的事情.

my @new_data = get_array_with_random_length();
splice(@new_data, @new_data, 0, undef x (9 - @new_data)); #pad @newdata to 9 elements w/ undefs (DBI will xlate to NULL)
$insert_sth->execute(@new_data);

这篇关于Perl插入MySQL DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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