You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中MySQL查询出现Unexpected identifier错误求助

问题分析与解决方案

Hey there! Let's break down what's going wrong here and fix it properly.

First, the immediate syntax error you're seeing: even though the SQL runs fine in phpMyAdmin, building the query with string concatenation in your Node.js code is risky and can break the JavaScript string structure. If the username variable ever contains special characters (like quotes, backslashes, or even unexpected formatting), it can split your SQL string open—making the JS engine parse part of the SQL as raw JavaScript code, hence the Unexpected identifier pointing at SELECT.

But the far bigger, critical issue here is SQL injection. Using string concatenation to build SQL queries is a massive security hole. Attackers could craft a malicious username that executes arbitrary SQL commands on your database, leading to data theft, corruption, or full system compromise.

The Fix: Use Parameterized Queries

Instead of string concatenation, leverage your database driver's built-in parameterized query support. This lets the driver handle escaping special characters automatically, eliminating both syntax errors and SQL injection risks entirely.

Here's how to rewrite your code correctly:

connection.query(
  "SELECT * FROM accounts_data WHERE new_username LIKE ?",
  [`%${username}%`], // Pass parameters as an array
  function (error, results, fields) {
    if (error) {
      console.error(error);
      return;
    }
    // Process your query results here
  }
);

Why This Works

  • The ? in the SQL acts as a safe placeholder for your parameter.
  • The driver takes the %${username}% value, properly escapes any dangerous characters, and inserts it safely into the query.
  • No more broken strings, no more SQL injection vulnerabilities.

To circle back to your original syntax error: even if your current username value (preloved_bys) looks harmless, it's likely that at some point (maybe a test case you ran earlier), username contained a character that broke the string—like a single quote or double quote. Parameterized queries eliminate this problem for good.

内容的提问来源于stack exchange,提问作者adit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:02:59