I am trying to build a function to add a new line to a SQL table, but when I run it I get the following:
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"
}
Here is the Database:
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
);
Here is my index.js call:
addRole(role) {
return this.connection.promise().query(
`INSERT INTO
role (title, salary, department_id)
VALUES
?`, role
)
};
And here is the function:
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();
}
I've tried adjusting it and I just can't figure out what is parsing incorrectly.
Seems like you are missing the brackets ( )
When insert into ... values you should put them within ( and ')'
its not a set command.
Update: Also the statement itself is wrong = not an ansi sql one.
This is wrong:
INSERT INTO role (title, salary, department_id) VALUES title = 'Red', salary = '50000', department_id = 3"
Instead it should be:
INSERT INTO role (title, salary, department_id) VALUES ('Red', '50000', 3)