简体   繁体   English

如何使用Perl将文本文件加载到MySQL中?

[英]How can I load a text file into MySQL using Perl?

Can anyone tell me how to read data from a text file and store it in a MySQL database using Perl? 谁能告诉我如何使用Perl从文本文件读取数据并将其存储在MySQL数据库中?

For example: 例如:

StudentID Name Dept
1 Chellappa IT
2 Vijay CSE
3 AAA ECE

99.9% of the time, the best approach for this kind of thing is to use the native bulk load tools that are specific to the target database. 99.9%的时间,针对这种情况的最佳方法是使用特定于目标数据库的本机大容量装载工具。 In this case, that would be LOAD DATA INFILE or its command line equivalent, mysqlimport . 在这种情况下,它将是LOAD DATA INFILE或等效的命令行mysqlimport

We can use Perl to massage the data into the correct format: 我们可以使用Perl将数据整理成正确的格式:

$ perl -wlne 'next if $. == 1; s/\s+/\t/g; print;' input.txt > output.txt

And then use mysqlimport to load it: 然后使用mysqlimport加载它:

$ mysqlimport [options] db_name output.txt

If your example really is as simple as what you posted, you could actually load your file as-is just by specifying some additional options for mysqlimport : 如果您的示例确实像您发布的示例一样简单,则实际上可以通过为mysqlimport指定一些其他选项来按原样加载文件:

$ mysqlimport --ignore-lines=1 --fields-terminated-by=' ' [options ...] db_name input.txt

Use DBI module to connect the database. 使用DBI模块连接数据库。 Read input file and split the value and store into an array. 读取输入文件并将其拆分并存储到数组中。 Now insert the array values into database. 现在将数组值插入数据库。

Here is a way (please note this code is not tested): 这是一种方法(请注意,此代码未经测试):

#!/usr/bin/perl
use warnings;
use strict;

use DBI;

my $dsn = "DBI:mysql:host=hostname; database=dbname; port=portname";

# database connection 
my $dbh = DBI->connect($dsn,"username","password") or die "Couldn't connect to MySQL server: $!";

my $query = 'INSERT INTO tableName (StudentID,Name,Dept) VALUES (?,?,?)';
my $sth = $dbh->prepare($query) or die "Prepare failed: " . $dbh->errstr();

open my $fh, "<", "file.txt" or die $!;
<$fh>;  #skip header

while (<$fh>)
{
    chomp;
    my @vals = split;
    $sth->execute(@vals);
}
close $fh;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM