简体   繁体   English

Ruby字符串中的(反斜杠,单引号)

[英]\' (backslash, single quote) in a Ruby string

I am using Ruby 1.8.7, trying to generate a string with the \\' characteres, in order to create a script for running in MySQL. 我正在使用Ruby 1.8.7,尝试使用\\'characteres生成一个字符串,以便创建一个在MySQL中运行的脚本。 The result should be like this: 结果应该是这样的:

INSERT INTO table (name, description) values ('Joana d\'Arc', '')

But i can't get just one backslash in a ruby string. 但是我不能在ruby字符串中只获得一个反斜杠。 Using the following code: 使用以下代码:

string = "INSERT INTO table (name, description) values ('Joana d\\'Arc', '')"

I got the following string: 我得到以下字符串:

INSERT INTO table (name, description) values ('Joana d\\'Arc', '')

And with: 与:

string = "INSERT INTO table (name, description) values ('Joana d\'Arc', '')"

I got this string: 我有这个字符串:

INSERT INTO table (name, description) values ('Joana d'Arc', '')

I recommend avoiding writing raw SQL, and, in this age, I'd use an ORM, even for simple DB use. 我建议避免编写原始SQL,并且,在这个时代,我使用ORM,即使是简单的数据库使用。 I highly recommend using the Sequel gem. 我强烈推荐使用Sequel宝石。 Borrowing from an example in the Sequel docs: 借用续集文档中的一个例子

sequel sqlite://temp
Your database is stored in DB...

Using SQLite, that started the sequel ORM in interactive mode, and created the SQLite database called "temp". 使用SQLite,以交互模式启动续集ORM,并创建名为“temp”的SQLite数据库。

ruby-1.9.2-p290 :001 > require 'logger'
 => true 
ruby-1.9.2-p290 :002 > DB.loggers << Logger.new(STDOUT)
 => [#<Logger:0x0000010160bc40 @progname=nil, @level=0, @default_formatter=#<Logger::Formatter:0x0000010160bc18 @datetime_format=nil>, @formatter=nil, @logdev=#<Logger::LogDevice:0x0000010160bbc8 @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#<IO:<STDOUT>>, @mutex=#<Logger::LogDevice::LogDeviceMutex:0x0000010160bba0 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Mutex:0x0000010160bb50>>>>] 

That enabled logging so we can see what Sequel will do as it talks to the database. 这启用了日志记录,因此我们可以看到Sequel在与数据库通信时会做什么。

ruby-1.9.2-p290 :003 > items = DB[:items] # Create a dataset
 => #<Sequel::SQLite::Dataset: "SELECT * FROM `items`"> 
ruby-1.9.2-p290 :004 > DB.tables
I, [2011-11-25T10:17:13.056311 #10130]  INFO -- : (0.000501s) SELECT * FROM `sqlite_master` WHERE (type = 'table' AND NOT name = 'sqlite_sequence')
 => [] 

Doh! 卫生署! I forgot to create the table... 我忘了创建表...

ruby-1.9.2-p290 :005 > DB.create_table :items do
ruby-1.9.2-p290 :006 >       primary_key :id
ruby-1.9.2-p290 :007?>     String :name
ruby-1.9.2-p290 :008?>     Float :price
ruby-1.9.2-p290 :009?>   end
I, [2011-11-25T10:17:20.985851 #10130]  INFO -- : (0.002372s) CREATE TABLE `items` (`id` integer PRIMARY KEY AUTOINCREMENT, `name` varchar(255), `price` double precision)
 => nil 

The table is created. 该表已创建。

ruby-1.9.2-p290 :010 > items = DB[:items] # Create a dataset
 => #<Sequel::SQLite::Dataset: "SELECT * FROM `items`"> 

That created a dataset, which is just a convenient way to talk to a table. 这创建了一个数据集,这只是一种与表交谈的便捷方式。

And, that's the payoff: 而且,这是回报:

ruby-1.9.2-p290 :011 > items.insert(:name => "Joan d'Arc")
I, [2011-11-25T10:17:45.186945 #10130]  INFO -- : (0.001981s) INSERT INTO `items` (`name`) VALUES ('Joan d''Arc')
 => 1

The ORM automatically escapes the characters for you. ORM会自动为您转义字符。 Your job is simplified greatly. 你的工作大大简化了。

ORMs are DBM aware, so they know when to escape for a particular database. ORM可以识别DBM,因此他们知道何时为特定数据库转义。 Your code doesn't change. 您的代码不会更改。 It's trivial to switch from SQLite to MySQL, Postgres, or even non-SQL databases. 从SQLite切换到MySQL,Postgres甚至非SQL数据库都是微不足道的。

The reason puts works is that it shows what is actually in the string. 放置工作的原因是它显示了字符串中的实际内容。 The bare console is showing the string escaped. 裸控制台显示字符串转义。 Try this on the console: 在控制台上试试这个:

"Joana d\\'Arc".size

You will get back 12. If both backslashes were there you should get 13. 你将回来12.如果两个反斜杠在那里你应该得到13。

Hauleth's answer should work. Hauleth的回答应该有效。

使用%q{}表示法编写它

string = %q[INSERT INTO table (name, description) values ('Joanna d\\'Arc', '')]

You could try this: 你可以试试这个:

string="INSERT INTO table (name, description) values ('Joana d"+"\\"+"'Arc','')"

I don't know if you must use 1.8.6, but if you can, update to 1.9.2. 我不知道你是否必须使用1.8.6,但如果可以,请更新到1.9.2。 Its much faster and stabler, along with many more features. 它更快更稳定,还有更多功能。

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

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