简体   繁体   English

用于SQL查询的Perl串联

[英]Perl concatenation for SQL query

I'm trying to transfer the content of a CSV file into a table in PostgreSQL using Perl. 我正在尝试使用Perl将CSV文件的内容传输到PostgreSQL中的表中。

I'm able to update my table successfully, but the terminal returns an error: 我能够成功更新我的表,但是终端返回一个错误:

Use of uninitialized value in concatenation (.) or string
Syntax error near ","
INSERT INTO test VALUES (, '', '', '', '',, )

Here is the code where it fails : 这是失败的代码:

for (my $i=0 ; $i<=50; $i++){
$dbh ->do("INSERT INTO test VALUES ('$LastName[$i]', '$Street[$i]', $Balance_account[$i])") ;

If more information is needed just ask them. 如果需要更多信息,请询问他们。 Sorry for the bad English. 对不起,英语不好。

-- Thomas -托马斯

Use placeholders, 使用占位符,

for (my $i=0 ; $i<=50; $i++){
  $dbh->do("INSERT INTO test VALUES (?,?,?)",
    undef,
    $LastName[$i], $Street[$i], $Balance_account[$i]
  );
}

Ideally, you should prepare the query and execute for each set of values, something like this: 理想情况下,您应该准备查询并针对每组值执行查询,如下所示:

my $sth = $dbh->prepare('INSERT INTO test VALUES (?,?,?)');

for (my $i=0 ; $i<=50; $i++){
  $sth->execute($LastName[$i], $Street[$i], $Balance_account[$i]);
}

My guess is that your error is being caused by not specifying the column names in your insert, while simultaneously having the wrong number/types of columns. 我的猜测是您的错误是由于未在插入中指定列名,而同时具有错误的编号/类型的列引起的。 I would expect the following Perl code to not error out: 我希望以下Perl代码不会出错:

for (my $i=0 ; $i<=50; $i++){
$dbh -> do("INSERT INTO test (lastname, street, balance) VALUES ('$LastName[$i]', '$Street[$i]', $Balance_account[$i])");

Here is what a working query might look like: 这是一个工作查询可能看起来像:

INSERT INTO test (lastname, street, balance)
VALUES
    ('Skeet', '100 Thatcher Street', 100.50);

It is generally considered bad practice to not include column names while doing an insert, because even if you get it right, it could easily break later on. 通常,在插入时不包括列名是不明智的做法,因为即使正确使用它,以后也很容易中断。

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

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