INSERT INTO error with mysql-node - mysql

This seems like it should be super easy, and I have been stuck for about two hours now. Four separate people have looked at and not found an obvious problem. So again I turn to the SO community.
Real simple - I am just trying to insert data in a mysql database via mysql-node. I am getting no connection errors, and SELECT works just fine. The code being used is:
exports.postNewCast = function(data, res) {
var query = "INSERT INTO cast (name, portrait, role, bio) VALUES ('" + data.name + "', '" + data.portrait + "', '" + data.role + "', '" + data.bio + "');";
console.log(query);
dbConnection.query(query, data, function(err, result) {
if (err) {
console.log(err);
} else {
sendResponse(res, "Cast Member Added", 201);
}
});
};
The error being logged is:
{ [Error: ER_PARSE_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 'cast (name, portrait, role, bio) VALUES ('Jessie', 'images/cast/marissa.jpg', 'L' at line 1]
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
index: 0 }
The weird part (for me) is that I can copy from my terminal window (where the server is running) the console.logged query string, and paste it into the mysql command line, and it works just fine. I have tried using GRANT to make sure the user server is running has permissions, and this did nothing. I have tried copying / pasting INSERT INTO syntax straight from working sources, and only replacing my data-specific fields. I have tried using the VALUES ? option, followed by a data object, and got the same result.
So what stupid mistake am I making?
Thanks.

Ilya Bursov had it correct, adding this answer for posterity. I am not sure if 'cast' is a reserved word or what, but I needed back ticks (" ` ") around the table name to get it working.

Try to put `` around each column name like this
"INSERT INTO cast (`name`, `portrait`, `role`, `bio`) VALUES ('" + data.name + "', '" + data.portrait + "', '" + data.role + "', '" + data.bio + "');";

Related

Why my database displays undefined even I inserted data in POSTMAN?

Below is my code for inserting data in MYSQL in ExpressJS.
router.post('/user', function (req, res) {
let sql = "INSERT INTO Member (id, Memb_ID, First_Name, Middle_Name, Last_Name, Address, url) VALUES (null, '" + req.body.Memb_ID + "', '" + req.body.First_Name + "', '" + req.body.Middle_Name + "', '" + req.body.Last_Name + "', '" + req.body.Address + "', '" + req.body.url + "')";
myDB.query(sql, function (err, results) {
if (err) throw err;
res.send({
Success: "Data inserted."
})
});
});
It inserts data in my database but my database looks like this
I don't know why it outputs like that. Here's my JSON
EDIT :
Here is my MYSQL Table
Can you make sure that the following is done?
The content-type header in the request has to be application/json
Use body-parser (or similar libraries) to parse JSON payloads -> You can print the req.body to validate this.
If you can confirm that the values are accessible, I would suggest escaping query values as mentioned in https://github.com/mysqljs/mysql#escaping-query-values (or in any mysql library that you use) - especially since it is a DML query.
(Also I assume that the fieldnames used in the query match with the ones in the database and are of the right datatype.)
In your image of postman call, it's clearly showing your content type is text.
Change Content-type to application/json in your postman call headers
Or you can select from body tab
As your body content was text as shown in your image, it was sending a plain text that leading to undefined in DB. But the server was expecting json.
Hope that helps.
See wether you have added #RequestBody annotation in your respective method signature in Controller...
check this 1's bcz i had same issue i resolved after adding this..
it may help you and others... also...

MySQL syntax error when inserting a row into database

I am trying to post a row into a mysql database using data from an express form but always get SQL syntax errors
router.post('/add', function(req, res, next) {
var title = req.body['title'];
var director = req.body['director'];
var release = req.body['release'];
var review = req.body['review'];
connection.query("INSERT INTO films.filmStore (title, director, review, release) VALUES ('" + title.toString() + "', '" + director.toString() + "', '" + review.toString() + "', '" + release.toString() + "');", function(err, result){
if(err) throw err;
console.log("1 record inserted");
});
res.redirect('/');
});
However I get an error
throw err; // Rethrow non-MySQL errors
Error: ER_PARSE_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 'release) VALUES ('Superman', 'Richard Donner', 'One of the best films of all tim' at line 1
I've tried everything I can think of but I'm new to SQL and can't figure out what's different from other examples I've seen.
release is a reserved keyword in mysql.
See: https://dev.mysql.com/doc/refman/8.0/en/keywords.html
Either alter the name of that column or use backticks:
"INSERT INTO films.filmStore (title, director, review, `release`) VALUES (..."

NodeJS + MySQL, can't access DB from application while INSERT but can access from terminal

I have a big data array which I try to insert into my database, then delete an old table and rename the new one. To do it faster I use TRANSACTION (it doesn't affect my problem, I tried without it) and make every MySQL query inside async.each function. In the callback of this async.each I do COMMIT (for transaction), deleting and renaming.
Usually I have 100000 or more rows to insert. If I use "SELECT COUNT(*)" in terminal I can see these rows insert quite slowly but somehow the process ends immediately when 1/4 of rows was inserted. Then I got a full table in one moment. I don't know why it happens, I'm OK with that but maybe this is the reason of my problem.
So this is my problem: I have no access to DB from Node while it makes inserting. But I still can access it from terminal where I can count rows, see a tables etc. If Node calls some other function with mysql query, this query will just wait until that big insert will end.
It's like Node code works in parallel but mysql queries work in just one thread. How can I fix this?
exports.insertSubscribers = function(data, db_name, done){
state.pool.query('START TRANSACTION');
async.each(data, function(row, cb){
state.pool.query('INSERT INTO new_' + db_name + ' (id, first_name, last_name, sex, city, country, photo_200) VALUES (' + "'" + row.id + "', " + "'" + row.first_name + "', " + "'" + row.last_name + "', " + "'" + row.sex + "', " + "'" + JSON.stringify(row.city) + "', " + "'" + JSON.stringify(row.country) + "', " + "'" + row.photo_200 + "'" + ')', cb);
}, end_transaction);
function end_transaction(){
state.pool.query('COMMIT', function(err){
if(err) return done(err);
state.pool.query('SHOW TABLES LIKE \'' + db_name + '\'', function(err, result){
if(result.length != 0){
state.pool.query('DROP TABLE ' + db_name, function(err){
if(err) return done(err);
state.pool.query('RENAME TABLE new_' + db_name + ' TO ' + db_name, function(err){
if(err) return done(err);
});
});
}else{
state.pool.query('RENAME TABLE new_' + db_name + ' TO ' + db_name, function(err){
if(err) return done(err);
});
}
});
});
}
};
MySQL by design only allows at most one query per connection at any given time. So what some MySQL drivers/modules do is to simply maintain an in-memory queue that is used when additional queries are made while another is in progress.
One possible workaround for this is to use multiple connections in a pool (the mysql and mysql2 modules have built-in pooling support for example) so that you can execute more queries in parallel.

Undefined method 'join' during mysql action (ruby/sinatra)

Undefined method 'join' during mysql action (ruby/sinatra)
Code:
rs = con.query('select * from userlog')
#logentry = ""
rs.each_hash { |h|
#logentry = #logentry + "ID: " + h['Id'] + "User: " + h['user'] + " - Time: " + h['datetime'] + " - Description: " + h['description'] + "<br>"
}
Error:
undefined method `join' for #<String:0x007f70585b68f8>
when I add ".to_s" to the "h[Id]" then I get blank results for the ID but the rest is shown.
It sounds like your 'userlog' table column name for the identifier is not 'Id', maybe 'id'. Otherwise it would have been selected normally.
I had similar problem. The reason was that table name was incorrect in database, and for some reason MySQL error messages were incorrect. Check all database, table and variable names.

MySQL Statement error in JSP

I have an issue with an sql statement and i dont know how to handle it. Here is the problem:
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`) VALUES ("
+ session.getAttribute("id")
+ ",'"
+ request.getParameter("RunningProjects")
+ "','"
+ request.getParameter("MainOrders")')";
The values are obtained from the post form which contains free text. The problem is, whenever a user enters characters like ', i will get an error because that tells the compiler that the value is over here(i suppose) and now look for the next value. I don't know how to include these characters and send them to database without having an error. Any help would be appreciated. Thank you.
The character ' is used to surround literals in MySQL. And if any data contains such character as part of it, we have to escape it. This can be done using Prepared Statement in Java.
Change your query code accordingly.
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`)
VALUES ( ?, ?,? )";
Now define a PreparedStatement instance and use it to bind values.
PreparedStatement pst = con.prepareStatement( query );
pst.setString( 1, session.getAttribute("id") );
pst.setString( 2, request.getParameter("RunningProjects") );
pst.setString( 3, request.getParameter("MainOrders") );
int result = pst.executeUpdate();
And, I suggest use of beans to handle business logic.
change
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`) VALUES ("
+ session.getAttribute("id")
+ ",'"
+ request.getParameter("RunningProjects")
+ "','"
+ request.getParameter("MainOrders")
+ "')";
I think you are using normal statement in your JDBC code. Instead, I would suggest you to use Prepared statement. Prepared statement is generally used to eliminate this kind of problem and caching issue. If you will use prepared statement I think your problem will be solved