How do you quote strings in Postgres

戏子无情 提交于 2019-12-02 11:59:55

As mentioned in the comments, most databases uses single quotes for string literals and double quotes for identifiers. MySQL is rather lax and will also accept double quotes for string literals but PostgreSQL is (thankfully) quite strict. So you want to use single quotes:

SnCl.all(:conditions => "col3 = 'xx'")

or using where:

SnCl.where("col3 = 'xx'")

or with sensible use of the database driver's quoting facilities:

SnCl.where("col3 = #{SnCol.connection.quote('xx')}")

And saving the best for last, the way sensible people do it using a placeholder or Hash arguments to where:

SnCl.where('col3 = ?', 'xx')
SnCl.where('col3 = :col3', :col3 => 'xx')
SnCl.where(:col3 => 'xx')

The final one would be the most idiomatic for Rails and the two above it would be useful for more complex conditions where chaining is either too cumbersome or doesn't work (such as when you need an OR in your WHERE clause).

You'd be better off using where for your condition. Have a look at

http://guides.rubyonrails.org/active_record_querying.html#conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!