\' Ruby 字符串中的(反斜杠、单引号)

发布于 2024-12-18 04:55:59 字数 645 浏览 4 评论 0原文

我正在使用 Ruby 1.8.7,尝试生成带有 \' 字符的字符串,以便创建在 MySQL 中运行的脚本。结果应该是这样的:

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

但是我不能在 ruby​​ 字符串中只得到一个反斜杠。使用以下代码:

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

我得到了以下字符串:

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

并且:

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

我得到了这个字符串:

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

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. 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. 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', '')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

日久见人心 2024-12-25 04:55:59

我建议避免编写原始 SQL,并且在这个时代,我会使用 ORM,即使是简单的数据库使用。我强烈建议使用 Sequel gem。借用 Sequel 文档中的 示例

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

使用 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>>>>] 

这启用了日志记录,因此我们可以看到 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')
 => [] 

哎哟!我忘记创建表...

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 

表已创建。

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

这就创建了一个数据集,这只是与表交互的一种便捷方式。

这就是回报:

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

ORM 会自动为您转义字符。你的工作大大简化了。

ORM 能够感知 DBM,因此它们知道何时对特定数据库进行转义。您的代码不会改变。从 SQLite 切换到 MySQL、Postgres 甚至非 SQL 数据库都很简单。

I recommend avoiding writing raw SQL, and, in this age, I'd use an ORM, even for simple DB use. I highly recommend using the Sequel gem. 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".

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.

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. Your job is simplified greatly.

ORMs are DBM aware, so they know when to escape for a particular database. Your code doesn't change. It's trivial to switch from SQLite to MySQL, Postgres, or even non-SQL databases.

神爱温柔 2024-12-25 04:55:59

put 起作用的原因是它显示了字符串中实际的内容。裸控制台显示转义的字符串。在控制台上尝试一下:

"Joana d\\'Arc".size

您将得到 12。如果两个反斜杠都在那里,您应该得到 13。Hauleth

的答案应该有效。

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.

Hauleth's answer should work.

亣腦蒛氧 2024-12-25 04:55:59

使用 %q{} 表示法编写

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

Write it using %q{} notation

string = %q[INSERT INTO table (name, description) values ('Joanna d\\'Arc', '')]
来世叙缘 2024-12-25 04:55:59

你可以试试这个:

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

我不知道你是否必须使用1.8.6,但如果可以的话,更新到1.9.2。它更快、更稳定,还有更多功能。

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. Its much faster and stabler, along with many more features.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文