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

mop*_*syd 2 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;
Run Code Online (Sandbox Code Playgroud)

问题是我的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);
Run Code Online (Sandbox Code Playgroud)

这是生成的错误:

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.
Run Code Online (Sandbox Code Playgroud)

Fil*_*efp 9

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

还要记住,"如果你"用来包装你的字符串的内容你的字符串不能包含任何空格,如果是这种情况你将需要转义"你希望成为你的字符串的一部分..请参阅下面的例子.

my $data = "hello, I can write \"quotes\" inside my string";
Run Code Online (Sandbox Code Playgroud)

虽然有更简单的选择,所以你不必担心逃避任何事情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;
};
Run Code Online (Sandbox Code Playgroud)

1.除非你计划}在你的字符串中使用..


阅读更多关于字符串和转义序列的信息: