简体   繁体   English

通过Ruby的SQL通配符

[英]SQL wildcards via Ruby

I am trying to use a wildcard or regular expression to give some leeway with user input in retrieving information from a database in a simple library catalog program, written in Ruby. 我试图使用通配符或正则表达式在使用Ruby编写的简单库目录程序中从数据库检索信息时给用户输入一些余地。

The code in question (which currently works if there is an exact match): 有问题的代码(如果存在完全匹配,则当前有效):

puts "Enter the title of the book"
title = gets.chomp
book = $db.execute("SELECT * FROM books WHERE title LIKE ?", title).first

puts %Q{Title:#{book['title']}
Author:#{book['auth_first']} #{book['auth_last']}
Country:#{book['country']}}

I am using SQLite 3. In the SQLite terminal I can enter: 我正在使用SQLite3。在SQLite终端中,我可以输入:

SELECT * FROM books WHERE title LIKE 'Moby%'

or 要么

SELECT * FROM books WHERE title LIKE "Moby%"

and get (assuming there's a proper entry): 并获取(假设输入正确):

Title: Moby-Dick
Author: Herman Melville
Country: USA

I can't figure out any corresponding way of doing this in my Ruby program. 在我的Ruby程序中,我找不到任何相应的方法。

Is it not possible to use the SQL % wildcard character in this context? 在这种情况下不能使用SQL %通配符吗? If so, do I need to use a Ruby regular expression here? 如果是这样,我是否需要在这里使用Ruby正则表达式? What is a good way of handling this? 有什么好的处理方法?

(Even putting the ? in single quotes ( '?' ) will cause it to no longer work in the program.) (即使将?放在单引号( '?' )也将使其在程序中不再起作用。)

Any help is greatly appreciated. 任何帮助是极大的赞赏。

(Note: I am essentially just trying to modify the sample code from chapter 9 of Beginning Ruby (Peter Cooper).) (注意:我实际上只是想修改Beginning Ruby (Peter Cooper)第9章中的示例代码。)

The pattern you give to SQL's LIKE is just a string with optional pattern characters. 您赋予SQL LIKE模式只是一个带有可选模式字符的字符串。 That means that you can build the pattern in Ruby: 这意味着您可以在Ruby中构建模式:

$db.execute("SELECT * FROM books WHERE title LIKE ?", "%#{title}%")

or do the string work in SQL: 或在SQL中使用字符串:

$db.execute("SELECT * FROM books WHERE title LIKE '%' || ? || '%'", title)

Note that the case sensitivity of LIKE is database dependent but SQLite's is case insensitive so you don't have to worry about that until you try to switch database. 请注意,LIKE的区分大小写取决于数据库,但是SQLite的区分大小写,因此在尝试切换数据库之前,您不必担心。 Different databases have different ways of dealing with this, some have a case insensitive LIKE, some have a separate ILIKE case insensitive version of LIKE, and some make you normalize the case yourself. 不同的数据库有不同的处理方式,有些数据库不区分大小写,例如LIKE,某些数据库有单独的LIKE版本的LIKE,不区分大小写,有些使您自己规范化大小写。

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

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