简体   繁体   中英

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.

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:

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.

Is it not possible to use the SQL % wildcard character in this context? If so, do I need to use a Ruby regular expression here? 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).)

The pattern you give to SQL's LIKE is just a string with optional pattern characters. That means that you can build the pattern in Ruby:

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

or do the string work in 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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