简体   繁体   English

在 sql 查询中使用引号 node.js

[英]use quotes in sql query node.js

I have my query like so:我有这样的查询:

let thequery = "insert into USERS (USERNAME) VALUES ('" + username + "')"

but when I insert the query into my database (I am storing the query for analytical purposes), it fails because of the quotes.但是当我将查询插入到我的数据库中时(我为了分析目的而存储查询),由于引号而失败。

var insertAnalyticsLogin = "insert into ANALYTICS (username, location, device, query, timeoflogin) VALUES ('" + username + "', '" + location + "', '" + device + "', '" + thequery + "', '" + timeoflogin + "')"

how can I fix this?我怎样才能解决这个问题? I tried converting thequery to toString() , but that was a useless attempt.我尝试将thequery转换为toString() ,但这是一次无用的尝试。 Any other ideas?还有其他想法吗?

edit:编辑:

error i am recieving is:我收到的错误是:

    sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'email@email.com')', '1/5/2022, 11:32:54 AM')' at line 1",
  sqlState: '42000',
  index: 0,
  sql: "insert into ANALYTICS (username, location, device, query, timeoflogin) VALUES ('email@email.com', 'n/a', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15', 'insert into USERS (USERNAME) VALUES ('email@email.com')', '1/5/2022, 11:32:54 AM')"

This is a great example of how using parameterized queries is better than using string-concatenation to format SQL queries.这是一个很好的例子,说明使用参数化查询比使用字符串连接来格式化 SQL 查询更好。 You can use parameter placeholders and then you never have to worry about the possible literal quote characters in your string variables.您可以使用参数占位符,然后您就不必担心字符串变量中可能存在的文字引号字符。

var insertAnalyticsLogin = "insert into ANALYTICS (username, location, device, 
  query, timeoflogin) VALUES (?, ?, ?, ?, ?)"

mysqlconn.query(insertAnalyticsLogin, 
  [username, location, device, thequery, timeoflogin],
  function(err, rows) {
    ...

You don't even need the single-quotes around the ?您甚至不需要?周围的单引号。 placeholders.占位符。 In fact, you must not quote the placeholders, or else it will try to insert a literal string "?"事实上,你不能引用占位符,否则它会尝试插入一个文字字符串“?” instead of treating it as a parameter.而不是将其视为参数。

Using query parameters makes your code easier to read and easier to write, without getting eyestrain trying to balance all those quotes-within-quotes.使用查询参数使您的代码更易于阅读和编写,而不会因为试图平衡所有引号内的引号而感到眼花缭乱。

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

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