在 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 注入攻擊。