简体   繁体   English

SQL 字符串中替换的正确语法是什么

[英]What is the correct syntax for replacements within a SQL string

I am attempting to do a basic search in my sqlite3 database with this JavaScript:我正在尝试使用此 JavaScript 在我的 sqlite3 数据库中进行基本搜索:

function search(query) {
  let sql = `SELECT * from tracks WHERE title LIKE '%${query}%'`

  db.sqlite.all(sql, [], (err, rows) => {
    console.log(rows)
  })
}

This works but is vulnerable to SQL injection.这可行,但容易受到 SQL 注入的影响。 I am trying to get the sqlite replacements parameter to work but I cannot get the syntax right.我正在尝试使 sqlite 替换参数起作用,但我无法正确使用语法。 Sqlite doesn't want to replace anything within the string literal. Sqlite 不想替换字符串文字中的任何内容。

// throws SQLITE_RANGE error
let sql = `SELECT * from tracks WHERE title LIKE '%$query%'`
db.sqlite.all(sql, {$query: query}, (err, rows) => {})

What is the correct way to write this so that it's not vulernable to SQL injection?编写此代码的正确方法是什么,使其不受 SQL 注入的影响?

What are these ||这些是什么|| for?为了? SQLite specialty? SQLite 特产? Yes, it is a way to concatenate strings in SQL - I do not know any other DBMS that uses that.是的,这是一种在 SQL 中连接字符串的方法——我不知道任何其他使用它的 DBMS。 So this solution only works for SQLite, but AFAIK not for MySql, Oracle, Transact SQL, ... it is not standard SQL. So this solution only works for SQLite, but AFAIK not for MySql, Oracle, Transact SQL, ... it is not standard SQL.

I think it is hard to know this trick with ||.我认为用 || 很难知道这个技巧。 There is a IMHO more understandable approach, that every developer easy understands:恕我直言,有一种更易于理解的方法,每个开发人员都很容易理解:

I would first change the value of the variable, then overgive it as a parameter to the query, like that the code should be readable - forgive me any oversight, because I am not a Javascript crack:我将首先更改变量的值,然后将其作为参数传递给查询,就像代码应该是可读的一样 - 请原谅我的任何疏忽,因为我不是 Javascript 破解:

function search(query) {
  let likePattern = `%${query}%` // or in the very old days = '%' + query + '%'
  let sql = `SELECT * from tracks WHERE title LIKE $likePattern`

  db.sqlite.all(sql, {$likePattern: likePattern}, (err, rows) => {})
}

PS: Someone had this idea already too in the comments of the question, so if anyone upvotes this, then upvote the others comment too. PS:有人在问题的评论中也已经有了这个想法,所以如果有人赞成这个,那么也赞成其他人的评论。

I figured it out我想到了

let sql = `SELECT * from tracks WHERE title LIKE '%' || $query || '%'`

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

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