如何在Perl中为'MySQL'查询转义'\ n'?

时间:2012-07-16 00:13:37

标签: mysql perl

我正在编写一个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.

3 个答案:

答案 0 :(得分:9)

如果您希望结果字符串包含双字节序列\r,则在将字符串包装在"之间时需要转义反斜杠。

另外请记住,如果使用"来包装字符串的内容,则字符串不能包含任何空闲",如果是这种情况,则需要每"my $data = "hello, I can write \"quotes\" inside my string"; 你想成为你的字符串的一部分..见下面的例子。

$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

}

1。 除非您打算在字符串中使用{{1}} ..


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

答案 1 :(得分:4)

首先,您确实需要use strict;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

答案 2 :(得分:0)

我更喜欢让mysql引用我的字符串 就像文本消息一样:

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