gpt4 book ai didi

Mysql插入包含双逗号的值

转载 作者:太空宇宙 更新时间:2023-11-03 11:47:02 25 4
gpt4 key购买 nike

我试图将值逐行插入到 MySQL 表中,该表是从 Perl 中的 CSV 文件中读取的。如果 CSV 文件中有任何字段为空,则会有两个连续的逗号。例如

Firstname,Lastname,Code,Phone,Email
fname1,lname1,123,34543,f1@gmail.com
fname2,lname2,344,45645,f2@gmail.com
fname3,lname3,454,,f3@gmail.com

第三行没有电话号码。所以有两个连续的逗号。当我们尝试使用以下命令插入 mysql 时,它失败了。

insert into table1 (Firstname,Lastname,Code,Phone,Email) values (fname3,lname3,454,,f3@gmail.com)

怎么做?

我使用以下代码来做到这一点。

open CSV, $file or die $!;
my @csv_content = <CSV>;
close CSV;
my $fields = "Firstname,Lastname,Code,Phone,Email";
my $table = "table1";

my $csv = Text::CSV->new();
foreach(@csv_content){
if($csv->parse($_)){
my @values = $csv->fields();
my $status = $csv->combine(@values);
my $line = $csv->string();

$statement = "INSERT INTO $table($fields) VALUES($line);";
$sth = $dbh->prepare( $statement );
$sth->execute() or die "$! $DBI::errstr";
}
}

最佳答案

我可能会这样写。我在您的 csv 文件中包含了空字段。我使用了 5 个占位符,'?',并且没有在循环内准备。只是在循环中执行。

my $csv = Text::CSV->new ( { binary => 1, eol => "\n" } );

my $file = 'blahblah';
open my $fh, $file or die "$file open failed: $!";

my $dbh = DBI->connect("dbi:SQLite:dbname=pedro.lite","","",
{PrintError => 1, AutoCommit => 0}) or die "Can't connect";


my $sth = $dbh->prepare(q{INSERT INTO table1 VALUES(?,?,?,?,?)})
or die $dbh->errstr;

<$fh>; # throw away header - first line
while (my $row = $csv->getline ($fh)) {
$sth->execute(@$row) or die $sth->errstr;
}

$dbh->commit or die $dbh->errstr;
close $fh or die "$file close failed: $!";
$sth->finish;

如果文件开头没有标题,请不要使用该行代码。

更新:这是我用来创建数据库的实际程序(使用 SQLite),它运行良好,即使使用双逗号(空字段)也是如此。

#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV_XS;
use DBI;

my $csv = Text::CSV_XS->new ( { binary => 1, eol => "\n" } );

my $file = 'j1.csv';
open my $fh, $file or die "$file open failed: $!";

my $dbh = DBI->connect("dbi:SQLite:dbname=pedro.lite","","",
{RaiseError => 1, PrintError => 0, AutoCommit => 0}) or die "Can't connect";

$dbh->do('DROP TABLE IF EXISTS table1');

$dbh->do(<<EOF);
CREATE TABLE table1 (
Firstname TEXT,
Lastname TEXT,
Code INTEGER,
Phone INTEGER,
Email TEXT)
EOF

my $sth = $dbh->prepare(q{INSERT INTO table1 VALUES(?,?,?,?,?)});

<$fh>; # throw away header - first line
while (my $row = $csv->getline ($fh)) {
$sth->execute(@$row);
}
$sth->finish;
$dbh->commit;
$dbh->disconnect;

close $fh or die "$file close failed: $!";

这里是表 1 的查询输出。

sqlite> .mode column
sqlite> .width 10 10 10 10 14
sqlite> .headers on
sqlite> select * from table1;
Firstname Lastname Code Phone Email
---------- ---------- ---------- ---------- --------------
fname1 lname1 123 34543 f1@gmail.com
fname2 lname2 344 45645 f2@gmail.com
fname3 lname3 454 f3@gmail.com
sqlite>

如您所见,它正确显示 fname3 没有电话号码。我使用了你的数据,就像它出现在你的帖子中一样插入到表 1 中。

关于Mysql插入包含双逗号的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37910583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com