【发布时间】:2022-01-16 00:23:23
【问题描述】:
我正在尝试构建一个向 SQL 表添加新行的函数,但是当我运行它时,我得到以下信息:
const localErr = new Error();
^
Error: 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 '`title` = 'Red', `sala
ry` = '50000', `department_id` = 3' at line 4
at PromiseConnection.query (C:\Users\corri\dev\classwork\Module-12\challenge\employee-tracker-M12HW\node_modules\mysql2\promise.js:93:22)
at DB.addRole (C:\Users\corri\dev\classwork\Module-12\challenge\employee-tracker-M12HW\db\index.js:62:42)
at addRole (C:\Users\corri\dev\classwork\Module-12\challenge\employee-tracker-M12HW\server.js:103:14)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ER_PARSE_ERROR',
errno: 1064,
sql: 'INSERT INTO \n' +
' role (title, salary, department_id)\n' +
' VALUES \n' +
" `title` = 'Red', `salary` = '50000', `department_id` = 3",
sqlState: '42000',
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 '`title` = 'Red
', `salary` = '50000', `department_id` = 3' at line 4"
}
这是数据库:
CREATE TABLE role (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(30) NOT NULL,
salary DECIMAL (10, 2),
department_id INT,
CONSTRAINT fk_department FOREIGN KEY (department_id) REFERENCES department(id) ON DELETE CASCADE
);
这是我的 index.js 调用:
addRole(role) {
return this.connection.promise().query(
`INSERT INTO
role (title, salary, department_id)
VALUES
?`, role
)
};
这里是函数:
async function addRole() {
// Pull options so user can select a department to correspond with this role
const [department] = await db.viewAllDepartments();
const departmentChoices = department.map(({ id, name }) => ({
name: name,
value: id
}));
const role = await inquirer.prompt([
{
type: 'input',
name: 'title',
message: 'What is the title of the role?'
},
{
type: 'input',
name: 'salary',
message: 'what is the salary of the role?'
},
{
type: 'list',
name: 'department_id',
message: 'Which department is this role a part of?',
choices: departmentChoices
}
]);
await db.addRole(role);
console.log(`Added ${role.name} to the database`);
mainMenu();
}
我已经尝试调整它,但我无法弄清楚是什么解析不正确。
【问题讨论】:
标签: javascript mysql sql parsing