2

我正在编写一个 Perl 脚本,以使用 OSX 中的 Automator 自动将 Excel 文档上传到 MySQL 数据库表中。我已经写了一个功能查询:

load data
local infile '/pathToFile/file.csv'
replace into table database.table
fields terminated by ','
enclosed by '"'
lines terminated by '\r'
ignore 1 lines;

问题是我的 Perl 脚本由于与\角色冲突而无法运行。我是一个 Perl 新手,所以我不知道如何正确地转义这个字符以使查询工作。

我的 Perl 脚本:

#!/usr/bin/perl

# PERL MODULE
use Mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# Set Variables
$host = "127.0.0.1";
$database = "database";
$tablename = "plugin_status";
$user = "user";
$pw = "password";

# PERL MySQL Connector
$connect = Mysql->connect($host, $database, $user, $pw);

# Run Query to update table
$myquery = "load data local infile '/pathToFile/file.csv' replace into table database.table fields terminated by ',' enclosed by '"' lines terminated by '\r' ignore 1 lines;";

# EXECUTE THE QUERY FUNCTION
$execute = $connect->query($myquery);

这是生成的错误:

String found where operator expected at perlfile.pl line 20, near ""load data local infile '/pathToFile/file.csv' replace into table database.table fields terminated by ',' enclosed by '"' lines terminated by '"
    (Missing operator before ' lines terminated by '?)
Backslash found where operator expected at perlfile.pl line 20, near "' lines terminated by '\"
    (Missing operator before \?)
syntax error at perlfile.pl line 20, near ""load data local infile '/pathToFile/file.csv' replace into table database.table fields terminated by ',' enclosed by '"' lines terminated by '"
Bad name after r' at perlfile.pl line 20.
4

3 回答 3

9

如果您希望生成的字符串包含两字节序列\r,则在将字符串包装在中间时需要转义反斜杠"

"还要记住,如果您用来包装字符串的内容,则您的字符串不能包含任何自由",如果是这种情况,您将需要转义每个"您想成为字符串一部分的内容。请参见下面的示例。

my $data = "hello, I can write \"quotes\" inside my string";

虽然有更简单的选择,所以你不必担心逃避任何东西1

$myquery = q{
  load data local infile '/pathToFile/file.csv'
  replace into table database.table
  fields
    terminated by ','
    enclosed by '"'
    lines terminated by '\r'
  ignore 1 lines;
};

1.除非你打算}在你的字符串中使用..


在此处阅读有关字符串和转义序列的更多信息:

于 2012-07-16T00:23:58.963 回答
4

首先,你真的需要use strict;and use warnings;。没有例外!反正:

…enclosed by '"'…

正如 refp 所指出的,perl 停止在那里解析你的双引号字符串。要么用反斜杠解除双引号,要么更好地将其包装在q{}here-doc中,而不是双引号。

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

# this
my $query = q{
  load data local infile '/pathToFile/file.csv'
    replace into table database.table
      fields terminated by ','
      enclosed by '"'
      lines terminated by '\r'
      ignore 1 lines;
};
# or this
my $query = <<'SQL';
  load data local infile '/pathToFile/file.csv'
    replace into table database.table
      fields terminated by ','
      enclosed by '"'
      lines terminated by '\r'
      ignore 1 lines;
SQL
于 2012-07-16T00:45:45.577 回答
0

我更喜欢让 mysql 引用我的字符串,就像一个 textarea 消息:

我的 $message = $dbh->quote($in{'message'});

于 2020-03-06T15:32:45.473 回答