Estoy tratando de construir una función para agregar una nueva línea a una tabla SQL, pero cuando la ejecuto obtengo lo siguiente:
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" }Aquí está la base de datos:
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);
Aquí está mi llamada index.js:
addRole(role) { return this.connection.promise().query( `INSERT INTO role (title, salary, department_id) VALUES ?`, role ) };Y aquí está la función:
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(); }Intenté ajustarlo y simplemente no puedo entender qué está analizando incorrectamente.
Parece que le faltan los corchetes ( ) Cuando inserte en ... valores, debe ponerlos dentro ( y ')' no es un comando establecido.
Actualización: también la declaración en sí es incorrecta = no es ansi sql.
Esto está mal:
INSERT INTO role (title, salary, department_id) VALUES title = 'Red', salary = '50000', department_id = 3"En su lugar, debería ser:
INSERT INTO role (title, salary, department_id) VALUES ('Red', '50000', 3)