Am curretly facing the following error when i try to query using express
code: 'ER_OPERAND_COLUMNS',
errno: 1241,
sqlMessage: 'Operand should contain 1 column(s)',
sqlState: '21000',
index: 0,
sql: "insert into quiz(user_pk,question,answer,choices,discussion) values (1, 'what is math', 'study of calculations', ('study of calculations', 'study of computing', 'study of books'), 'its amaizing')"
}
routes
.post((req, res) => {
query =
"insert into quiz(user_pk,question,answer,choices,discussion) values ?";
values = [Object.values(req.body)];
console.log(values)
connection.query(
query,
[values],
(err, result) => {
if (err) throw err;
res.json({ message: "question sussefully created" });
}
);
});
data i want to insert
{
"user_pk":1,
"question":"what is math",
"answer":"study of calculations",
"choices":["study of calculations","study of computing","study of books"],
"discussion":"its amaizing"
}
example of query i want to perform
insert into quiz(user_pk,question,answer,choices,discussion)
values(1,'what is physics?','study of matter','["study of matter","study of dances","study of matter"]','lorem ipsum dolor lorem');
here is the quiz table
CREATE TABLE if NOT EXISTS quiz(
quiz_pk INT NOT NULL AUTO_INCREMENT,
user_pk INT NOT NULL,
question VARCHAR(255) NOT NULL,
answer VARCHAR(255) NOT NULL,
choices JSON NOT NULL,
discussion VARCHAR(255) NOT NULL,
PRIMARY KEY (quiz_pk),
FOREIGN KEY (user_pk) REFERENCES user(user_pk)
);
please help me out.Thanks alot
Related
I'm trying to run a simple application with Express, Sequelize, and MySQL
I get this error:
Executing (default): CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
err: Error
at Query.run (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\dialects\mysql\query.js:52:25)
at C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\sequelize.js:313:28
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async MySQLQueryInterface.createTable (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\dialects\abstract\query-interface.js:94:12)
at async Function.sync (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\model.js:939:5)
at async Sequelize.sync (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\sequelize.js:377:9) {
name: 'SequelizeDatabaseError',
parent: 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 'NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1
at Packet.asError (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packets\packet.js:728:17)
at Query.execute (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\commands\command.js:29:26)
at Connection.handlePacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:456:32)
at PacketParser.onPacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:85:12)
at PacketParser.executeStart (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:92:25)
at Socket.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
at Socket.Readable.push (internal/streams/readable.js:204:10) {
code: 'ER_PARSE_ERROR',
errno: 1064,
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 'NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1",
sql: 'CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY
(`id`)) ENGINE=InnoDB;',
parameters: undefined
},
original: 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 'NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1
at Packet.asError (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packets\packet.js:728:17)
at Query.execute (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\commands\command.js:29:26)
at Connection.handlePacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:456:32)
at PacketParser.onPacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:85:12)
at PacketParser.executeStart (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:92:25)
at Socket.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
at Socket.Readable.push (internal/streams/readable.js:204:10) {
code: 'ER_PARSE_ERROR',
errno: 1064,
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 'NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1",
sql: 'CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY
(`id`)) ENGINE=InnoDB;',
parameters: undefined
},
sql: 'CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;',
parameters: {}
}
[nodemon] clean exit - waiting for changes before restart
so here is my connection:
const { Sequelize } = require('sequelize');
require('dotenv').config()
const Sequelized = new Sequelize(
process.env.DATABASE_NAME,
process.env.USER_NAME,
process.env.PASSWORD,
{
dialect: 'mysql',
host: process.env.DATABASE_HOST
}
);
module.exports = Sequelized;
and here is my entry-point for the app
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const router = require('./routes/tasks');
const Sequelized = require('./utiles/database');
const app = express();
require('dotenv').config();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(router);
Sequelized.sync()
.then((result) => {
console.log('result: ', result);
app.listen(3001, () => console.log('App is Listining on port 3001'));
})
.catch((err) => {
console.log('err: ', err);
});
and here is my task model definition
const { DataTypes } = require('sequelize');
const Sequelized = require('../utiles/database');
const Task = Sequelized.define('task', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.STRING,
allowNull: false,
},
status: {
type: DataTypes.NUMBER,
allowNull: false,
},
createdBy: {
type: DataTypes.NUMBER,
allowNull: true
}
});
module.exports = Task;
and here is my attempt to run it
const Task = require("../models/task");
exports.CreateTask = (req, res) => {
const { title, description, userId } = req.body;
Task.CreateTask({
title,
description,
createdBy: userId,
status: 1
}).then(res => {
console.log('res: ', res)
}).catch((err) => {
console.log('err: ', err);
})
}
this issue happened only when I tried to use Task, to start creating tasks, I think the issue is re-priducable,
any help is appreciated for sure,
thanks
The problem is that you defined the model Taks and in the last piece of code, you export a function named CreateTask.
But inside this arrow function, you try to create a new Task but you're calling CreateTask again. And you also missed to specifie for title and description what are the keys you want to assign those values.
You should use Task.creat(... like this:
const Task = require("../models/task");
exports.CreateTask = (req, res) => {
const { title, description, userId } = req.body;
Task.create({
title: title,
description: description,
createdBy: userId,
status: 1
}).then(res => {
console.log('res: ', res)
}).catch((err) => {
console.log('err: ', err);
})
}
I successfully connected to a local MySQL server using the new x-authentication. I have a products table with the following schema (DDL):
CREATE TABLE `products` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`description_he` text,
`description_en` text,
`display_name_he` varchar(45) DEFAULT NULL,
`display_name_en` varchar(45) DEFAULT NULL,
`image_path` varchar(255) DEFAULT NULL,
`price` smallint unsigned NOT NULL,
`is_visible` tinyint NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COMMENT='contains information about products'
I tried to insert the following javascript object into this table:
Product {
productID: null,
productName: 'product2',
descriptionHE: 'תיאור המוצר',
descriptionEN: 'product description',
displayNameHE: 'מוצר',
displayNameEN: 'Product',
imagePath: 'assets/images/facebook-512.png',
price: 400
}
I did this using the following code:
let table = this.session.getSchema('...').getTable('products')
return table.insert(
'id', 'name', 'description_he', 'description_en', 'display_name_he', 'display_name_en', 'image_path', 'price', 'is_visible')
.values(
5,
product.name,
product.descriptionHE,
product.descriptionEN,
product.displayNameHE,
product.displayNameEN,
product.imagePath,
product.price,
1)
.execute()
.catch((err) => {
console.log(err);
})
This catches the following error:
Error: Wrong number of fields in row being inserted
at SqlResultHandler.BaseHandler.<computed> (C:\Users\...\node_modules\#mysql\xdevapi\lib\Protocol\InboundHandlers\BaseHandler.js:119:17)
at Array.entry (C:\Users\...\node_modules\#mysql\xdevapi\lib\Protocol\InboundHandlers\BaseHandler.js:90:29)
at WorkQueue.process (C:\Users\...\node_modules\#mysql\xdevapi\lib\WorkQueue.js:75:19)
at Client.handleServerMessage (C:\Users\...\node_modules\#mysql\xdevapi\lib\Protocol\Client.js:208:21)
at Client.handleNetworkFragment (C:\Users\...\node_modules\#mysql\xdevapi\lib\Protocol\Client.js:252:14)
at TLSSocket.<anonymous> (C:\Users\...\node_modules\#mysql\xdevapi\lib\Protocol\Client.js:90:36)
at TLSSocket.emit (events.js:315:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at TLSSocket.Readable.push (internal/streams/readable.js:223:10) {
info: {
severity: 0,
code: 5014,
sqlState: 'HY000',
msg: 'Wrong number of fields in row being inserted'
}
}
I tried playing with the arguments and simplifying the table schema a bit but I can't find the error yet. Do you know how can I debug the query sent to the SQL server to figure out why it's failing?
The problem was that I used product.name instead of product.productName.
Conclusion, use typescript. :)
So we have 2 tables:
listings
users
Currently, i'm trying to retrieve all the information of the given users id where the fk_poster_id of the listings table is the foreign key with reference made to the users id by using the GET method.But when i try to execute the codes, i receive [] as the output. Is there a way to solve this?
Here's my current sql codes
DROP DATABASE snapsell;
CREATE DATABASE IF NOT EXISTS `snapsell`;
USE `snapsell`;
DROP TABLE IF EXISTS `users`;
DROP TABLE IF EXISTS `listings`;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
UNIQUE (username),
profile_pic_url VARCHAR(1000) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB;
-- THESE ARE JUST EXAMPLES AND TEST KITS.TO BE REMOVED BEFORE PRESENTATION.
INSERT INTO users (username, profile_pic_url) VALUES
("steve_jobs","https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Steve_Jobs_Headshot_2010-CROP2.jpg/800px-Steve_Jobs_Headshot_2010-CROP2.jpg"),
("barack_obama","https://upload.wikimedia.org/wikipedia/commons/e/e9/Official_portrait_of_Barack_Obama.jpg"),
("kim_jung_un","https://upload.wikimedia.org/wikipedia/commons/d/d0/Kim_Jung-Un_-_Inter_Korean_Summit%28cropped%29_v1.jpg"),
("lee_kuan_yew","https://upload.wikimedia.org/wikipedia/commons/0/0f/Lee_Kuan_Yew.jpg");
CREATE TABLE listings (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
description_i VARCHAR(1000) NOT NULL,
price INT(6) NOT NULL,
fk_poster_id INT NOT NULL,
KEY fkPosterID (fk_poster_id),
CONSTRAINT FOREIGN KEY (fk_poster_id) REFERENCES users(id) ON DELETE NO ACTION ON UPDATE NO ACTION,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB;
-- THESE ARE JUST EXAMPLES AND TEST KITS.TO BE REMOVED BEFORE PRESENTATION.
INSERT INTO listings (title, description_i, fk_poster_id, price) VALUES
("iPhone 6s USED","In good condition. Camera and screen not working.","2","250"),
("Samsung S7 NOT USED","In bad condition. Screen fully smashed. Can't even operate.","3","10000");
CREATE TABLE offers (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
fk_offeror_id INT NOT NULL,
KEY fkOfferID (fk_offeror_id),
CONSTRAINT FOREIGN KEY (fk_offeror_id) REFERENCES users(id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=INNODB;
SELECT * FROM users;
SELECT * FROM listings;
My current controller codes
var express = require('express');
var app = express();
const userJs = require('../model/user')
const listingJs = require('../model/listing')
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json()); //parse appilcation/json data
app.use(urlencodedParser);
app.get("/users/:user_id/listings/",(req,res) => {
var user_id = req.params.id;
userJs.getListingsByUserID(user_id, (error,results) => {
if (error) {
res.status(500).send("Internal Server Error")
}
res.status(200).send(results);
});
})
And my current user.js codes
var db = require('./databaseConfig.js')
const users = {getListingsByUserID: function (user_id, callback) {
const getListingsByUserIDQuery = 'SELECT u.id,l.title,l.description_i,l.price,l.fk_poster_id,l.created_at FROM listings l INNER JOIN users u ON u.id = l.fk_poster_id WHERE u.id = ?;';
db.query(getListingsByUserIDQuery,[user_id],(error,results) => {
if (error) {
callback(error,null);
return;
};
callback(null,results);
})
}
module.exports = users;
Just try to use Promise instead of callback like this:
const users =
{
function getListingsByUserID(user_id)
{
return new Promise((resolve, reject) =>
{
db.query(getListingsByUserIDQuery,[user_id],(error,results) =>
{
if (error)
{
return reject(error);
}
else
{
return resolve(results);
}
});
});
});
};
If you want result through callback method then try callback(null,results[0]);
I use node.js and mysql module.When I execute the following code I want the table_name to be set to a variable, not a static table name. For example I want table_name to be todays date.
connection.query(
"CREATE TABLE `<table_name>` (" +
" `title` varchar(50) NOT NULL,"+
" `text` varchar(50),"+
" `created` timestamp NULL,"+
" PRIMARY KEY (`title`));"
);
Is it possible to set table name as a variable in mysql module for node.js?
Best Regards
The module has built in methods to handle your case, you need to escape the variables like this:
var tableName = 'THETABLE';
connection.query('CREATE TABLE ?? (column_name1 data_type(size), column_name2 data_type(size), column_name3 data_type(size))', [tableName], function (error, results) {
// error will be an Error if one occurred during the query
// results will contain the results of the query (if any)
});
You can read more about this feature here:
https://github.com/felixge/node-mysql/#escaping-query-identifiers
async function createTable(db_connection,tableName) {
await new Promise((resolve, reject) => {
db_connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
db_connection.query('CREATE TABLE ?? (doc_source_type varchar(255) default null,
doc_id varchar(255) default null, company varchar(255) default null)',
[tableName],
function(err, results) {
if (err) {
console.log(err.message);
reject(err);
}
else{
console.log("Table created successful");
resolve(results);
}
});
});
});
}
or you can even try different approach
async function setTable(db_connection,tableName) {
await new Promise((resolve, reject) => {
db_connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
let createTodos =`create table if not exists ??(
id int primary key auto_increment,
doc_id varchar(255) default null,
doc_source_type varchar(255) default null,
company varchar(255) default null,
customer varchar(255) default null,
rubric_version varchar(255) default null,
assessment_type varchar(255) default null,
indexed_at datetime default null,
assessment_date datetime default null,
industry_type varchar(255) default null
)`;
//console.log(createTodos);
db_connection.query(createTodos, [tableName], function(err, results) {
if (err) {
console.log(err.message);
reject(err);
}
else{
console.log("Table created successful");
resolve(results);
}
});
});
});
}
I am trying to insert data into the MySQL user table through node js, I am using
and following
https://github.com/felixge/node-mysql#escaping-query-values
Below is my code, I don't really know what went wrong, I couldn't insert data through postData query, but it works if I try to execute the test query.
Why isn't the postData query working?
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : 3306,
database : 'csc309',
user : 'root',
password : 'root'
});
connection.connect();
var postData = {username: 'user4',
firstname: 'first',
lastname: 'last',
password: 'password',
email: 'test2#email.com'};
/*
var test = connection.query('INSERT INTO user (username, firstname, lastname, password, email) VALUES
("user4", "first", "last", "password", "sdfsdf#hotmail.com")');
*/
var query = connection.query('INSERT INTO user VALUES ?', postData, function(err, result) {
console.log('The solution is: ', result);
});
Here is my user sql user table.
create table user (
id int AUTO_INCREMENT PRIMARY KEY,
username varchar(40) UNIQUE NOT NULL,
firstname varchar(40) NOT NULL,
lastname varchar(40) NOT NULL,
password varchar(100) NOT NULL,
created_at datetime NOT NULL,
email varchar(40) UNIQUE NOT NULL,
reputation int DEFAULT 0,
mailing_address varchar(100),
phone varchar(20),
gender varchar(10),
admin tinyint default 0 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
If you want to insert a row with explicitly specified values passing an object to a escaped query, you should use the INSERT ... SET form:
var query = connection.query('INSERT INTO user SET ?', postData, function(err, result) {
console.log('The solution is: ', result);
});
The resulting query will look like:
INSERT INTO user SET `username` = 'user4', `firstname` = 'first', `lastname` = 'last', `password` = 'password', `email` = 'test2#email.com'