在 Ruby 中拼接 SQL 查询语句通常使用字符串插值或字符串连接的方式。以下是一些常用的 SQL 拼接技巧:
name = "John"
age = 30
sql_query = "SELECT * FROM users WHERE name = '#{name}' AND age = #{age}"
conditions = []
conditions << "name = 'John'" if name
conditions << "age = #{age}" if age
sql_query = "SELECT * FROM users WHERE " + conditions.join(" AND ")
name = "John"
age = 30
sql_query = "SELECT * FROM users WHERE name = ? AND age = ?"
result = ActiveRecord::Base.connection.exec_query(sql_query, "SQL", [[nil, name], [nil, age]])
User.where(name: "John").where(age: 30).to_sql
这些技巧可以根据具体的需求和场景来选择使用,建议在拼接 SQL 查询语句时尽量避免直接拼接用户输入的数据,以防止 SQL 注入攻击。