如何在Perl中将数组数据插入MySQL? [英] How can I insert array data into MySQL in Perl?
本文介绍了如何在Perl中将数组数据插入MySQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下脚本解析文本文件。
I parse a text file with the script below.
如何将数组数据插入MySQL表?
How to insert the array data to MySQL table?
我已经学习了Perl MySQL DBI连接方法。而且我可以成功连接到本地MySQL数据库。我可以使用MySQL命令行创建表。
I already learned Perl MySQL DBI connect method. And I can connect to local MySQL DB successfully. I can create the table with MySQL command line.
#!C:\Perl\bin\perl.exe
use strict;
use warnings;
while ( <DATA> ) {
my @rocks = split(/\s+/, $_);
foreach my $rock (@rocks) {
$rock = "\t$rock "; # put a tab in front of each element of @rocks
$rock .= "\n"; # put a newline on the end of each
print $rock ;
}
}
__DATA__
A B C D
E F G H
我想要表浏览结果。
Item1 Item2 Itme3 Item4
A B C D
E F G H
推荐答案
use strict;
use warnings;
use DBI;
my $dbh = DBI->connect(
'DBI:mysql:database=test;host=localhost',
'root',
'YOUR_PASSWORD',
{ RaiseError => 1, AutoCommit => 1 },
);
my $sql = 'INSERT INTO foo (Item1,Item2,Item3,Item4) VALUES (?,?,?,?)';
my $sth = $dbh->prepare($sql);
while (<DATA>){
chomp;
my @vals = split /\s+/, $_;
$sth->execute(@vals);
}
__END__
A B C D
E F G H
这篇关于如何在Perl中将数组数据插入MySQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文