I am requesting a bigint from my database. However, Node.js alters the value of my request, so that my program doesn't work.
Here's my code:
let query = `SELECT transcriptchannel FROM guilds WHERE guild_id = 933323734322913301;`
sql.query(query, function(err, result){
if(err) throw err;
console.log(result);
}
The console logs:
[ RowDataPacket { transcriptchannel: 946134226196123600 } ]
However, if i run the same statement in PHPmyAdmin, it looks like the following:
SELECT transcriptchannel FROM guilds WHERE guild_id = 933323734322913301;
it returns:
946134226196123658
Why does Node.JS round the value up and how do i prevent it?
This happens when the number is greater than Number.MAX_SAFE_INTEGER.
Please try following and see if you are getting expected value:
const sql = mysql.createConnection({supportBigNumbers: true, bigNumberStrings: true});
reference - https://github.com/mysqljs/mysql
Related
I'm having trouble sending a secure SQL query to mysql server from nodeJS.
When using this piece of code:
let test = "chart1yusd"
db.query('SELECT '+ test +' FROM coinDetail WHERE id = ?',[
requestID,
],function(err, result){
console.log(result)
res.send(result);
});
I get the correct output:
[ RowDataPacket {
chart1yusd:
'[[1589846400000,0.118103090573034],[1590710400000,0.14990946026516133],[1591574400000,0.13832947332698067],[1592438400000,0.14626382998803866],[1593302400000,0.12312689681792738],[1594166400000,0.13064585929472963],[1595030400000,0.15134667446052835],[1595894400000,0.14511870584962466],[1596758400000,0.2044381065518002],[1597622400000,0.27718349745013865],[1598486400000,0.24733539468353966],[1599350400000,0.15428765583919232],[1600214400000,0.18333082011361068],[1601078400000,0.16554945200142196],[1601942400000,0.15536379703562367],[1602806400000,0.17817122591867382],[1603670400000,0.14901182983793498],[1604534400000,0.15243756831164262],[1605398400000,0.25106271236512906],[1606262400000,0.22676917209412703],[1607126400000,0.22559988488004115],[1607990400000,0.3198349358258863],[1608854400000,0.28175278764129286],[1609718400000,0.48270197854575086],[1610582400000,0.5562085890730089],[1611446400000,0.4835010798224596],[1612310400000,0.46142579899847125],[1613174400000,0.7327130188547617],[1614038400000,0.7803392989162374],[1614902400000,1.2216997730172996],[1615766400000,1.1508817751759253],[1616630400000,1.2024881678362118],[1617494400000,1.1159947150076852],[1618358400000,2.3093588705698713],[1619222400000,1.9654124655802336],[1620086400000,2.0674879115219373],[1621230497000,1.3424936470400413]]' } ]
But when using this piece of code (the more secure version against sql injection):
let test = "chart1yusd"
db.query('SELECT ? FROM coinDetail WHERE id = ?',[
test, requestID,
],function(err, result){
console.log(result)
res.send(result);
});
I get this output, and not the data I want like before.
[ RowDataPacket { chart1yusd: 'chart1yusd' } ]
What did I do wrong and how can I fix this?
The query SELECT ? FROM coinDetail WHERE id = ? is not a valid MySQL prepared statement, because only literal values can be represented by ? placeholders. Database objects, including column and table names, can't have placeholders.
So, you are basically stuck using your first version. If you know a priori that the chart1yusd column is what you want to select, then just hard code it:
SELECT chart1yusd FROM coinDetail WHERE id = ?
You cannot use placeholders for columns, only for values. To dynamically select the column of interest, just select all columns, and then pick the one you need:
let test = "chart1yusd"
db.query('SELECT * FROM coinDetail WHERE id = ?', [
requestID,
], function(err, result){
console.log(result[0][test])
res.send(result[0][test]);
});
I am trying to write a simple login page using node.js, HTML, and MySQL. A problem I ran into was adding entries to my sql db.
con.connect(function(err) {
if (err) throw err;
});
app.post('/create', function(req, res) {
var info ={
"usernamec":req.body.USERC,
"passwordc": req.body.PASSC
}
con.query('INSERT INTO users SET ?',info, function(err, result){
console.log(result);
});
});
Everything seems to be working except for the actual query, which returns undefined. What could I be doing wrong? The picture below is my database.
solution:
Change or Modify in Column name when you can assign the values (usernamec, passwordc) this one.
let info ={"username": req.body.USERC,"password": req.body.PASSC}
whenever you can insert the data Column name will be same as the Database table Col name.means Both are same not different
Firstly, please check your request params(USERC, PASSW)DataType and
Values.
then Second thing, console the error
con.query('INSERT INTO users SET ?',info, function(err, result){
if(err)
console.log(err);
console.log(result);
});
});
InCase Query Error you can get and resolved it.
Another Simple Way runs the Query in PHPMyadmin Manually.
Example:
INSERT INTO users SET `username`= 1 and `password` =`HELLO MYSQL`;
I have been trying to setup my Nodejs MySQL database configuration. I found this passport.js config for MySQL on Github. The config works properly but there is a part that I do not understand.
var insertQuery = "INSERT INTO users ( email, password ) values ('" + email +"','"+ password +"')";
console.log(insertQuery);
connection.query(insertQuery,function(err,rows){
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
I am confused about the insertID field. The table I am using does not have a field called insertID. It does however have a field named ID. I tried changing that line to
newUserMysql.id = rows.Id;
bu doing so gives me:
Error: Failed to serialize user into session
Leaving it as it is gives me no error
Looks like insertID has nothing to do with the ID field of my table but I do not understand what it means
That probably represents LAST_INSERT_ID() which is the ID of the last row inserted.
The response of an INSERT is not "rows" but a result object, so maybe better named it'd be:
connection.query("...", function(err, result) {
newUserMysql.id = result.insertId;
return done(null, newUserMysql);
});
It's important to note that using Promises dramatically simplifies your code, and async/await can take that even further. This could be as simple as:
let result = await connection.query("...");
newUserMysql.id = result.insertId;
return newUserMysql;
Where that's inside an async function with a Promise-driven database library like Sequelize. You're not handling the potential errors in your first case. In the second you'll get exceptions which will wake you up when there's problems.
user_id=3;
//Delete from table query working perfect
db.query("DELETE FROM table WHERE user_id=" + user_id, function(dberr,dbres){
addUserInventories(detail, req, function(err,invres){
getHomePageDataWithInvntory(req, function(request, response){
callback(null, response);
});
});
});
//Here add record in table
function addUserInventories(detail, req, callback){
//After insertion called following and working perfect
return callback(null, null);
});
//Here retrieve record from table but not getting result after delete and insert operation
function getHomePageDataWithInvntory(req, callback){
user_id=3;
db.query("SELECT * FROM table WHERE user_id=" + user_id, function(err, results){
callback(null, results); //Here result getting empty array
});
});
In above code Delete record and Insert record work perfect but Retrieving record is not working.
Note : There is no any syntax error in SQL Query and In log file it print SELECT * FROM table WHERE user_id=3
When I got this kind of error, I always save them with the same process :
console.log your query string before using it
Use a database client like Sequel Pro, MySQL Workbench for sql
Copy paste your query manually in the client and run it
Generally, you'll get a syntax error, just solve it in the database client and your solution should work
Database client is not mandatory as you can run the query with command line, but the client will be a simpler interface for you and is more likely to give you more details on your syntax error.
Can you try this process ? If you don't succeed in solving the syntax error in the database client, you can put the query here so we can help you
Just in case : with your example, I'll use this pattern to log the query if you have trouble to do it, this give you an idea of how to do it in your code
//Here retrieve record from table but not getting result after delete and insert operation
function getHomePageDataWithInvntory(req, callback){
user_id=3;
var queryString = "SELECT * FROM table WHERE user_id=" + user_id;
console.log(queryString);
db.query(queryString, function(err, results){
callback(null, results); //Here result getting empty array
});
});
I am running a query which gives me confusing results. I have a node.js server which takes some user input from a form on the client side and uses socket.io to get the input on the server. here is the function which runs after receiving user input
databaseCheck(data);
function databaseCheck(userInput){
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '12.34.56.78',
user : 'user',
password : 'password',
database : 'db'
});
connection.connect();
var query = connection.query('SELECT * from `table` WHERE `email` = userInput', function(err, rows, fields) {
if (!err) console.log(rows[0].username);
else console.log("connection failure");
});
connection.end();
}
So when ever I use this code, it keeps printing "connection failure" to the screen. It doesn't happen when I replace userInput with the "example#email.com" so I'm guessing there is some problem with using the variable userInput in the query. Can someone tell me what is wrong with my code?
Not only do you need to pass the userInput by appending it to the string, you need to escape it so that the query recognizes it as a string:
connection.connect();
var query = 'SELECT * from `table` WHERE `email` = ' + JSON.stringify(userInput);
console.log(query);
connection.query(query, function(err, rows, fields) {
if (!err) console.log(rows[0].username);
else console.log(err.name, err.message);
});
connection.end();
It also helps to make the error message more informative by displaying the actual error instead of a generic message.
Lastly, put connection.end(); inside the callback. According to what you said, it appears to work like you had it but it's generally a bad idea to end a connection before an asynchronous process using the connection has called back.
Ignore my last comment, it appears I was wrong in this particular case. According to the repository documentation, it says:
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.
Try this for testing and resolution. Printing to the log will let you see what you are putting in the query.
var querystring = "SELECT * from table WHERE email LIKE " +
userInput;
console.log(querystring);
var query = connection.query(querystring, function(err, rows, fields) {...