I'm using MySQL for the first time, and I'm struggling to properly preparing statements and escaping query values. Here's where I'm at:
connection.connect();
formatDate(function(date){
var sql = "INSERT INTO coffee_tbl (coffee_name, coffee_type, submission_date) VALUES ?";
var inserts = [req.param('name'), req.param('type'), date];
var queryString = mysql.format(sql, inserts);
console.log(queryString)
connection.query(queryString, function(err, results){
if(err) serverError(res, err);
else{
res.redirect('/view_coffee');
}
});
});
connection.end();
I'm using the 'mysql' node.js module by felixge.
You need a ? per value. Also, be sure to use a connection pool.
formatDate(function(date){
var sql = [
"INSERT INTO coffee_tbl SET",
" coffee_name=?",
",coffee_type=?",
",submission_date=?"
].join('');
var inserts = [req.param('name'), req.param('type'), date];
pool.getConnection(function(err, connection) {
if(err) return console.error(err);
connection.query(sql, inserts, function(err, results) {
connection.release();
if(err) return console.error(err);
res.redirect('/view_coffee');
});
});
});
To setup a connection pool:
var pool = mysql.createPool({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASS,
database: process.env.MYSQL_NAME,
connectionLimit: 8
});
Use environment variables for your mysql authentication information so as to not commit authentication information to a repo.
You only have one placeholder in your sql var, but you are trying to pass three values in your inserts var. You want to modify your sql var to have three placeholder like this:
var sql = "INSERT INTO coffee_tbl (coffee_name, coffee_type, submission_date) VALUES (?, ?, ?)";
Related
I want to display all the values from two tables from my database and display it as console.log. If I write a single query in var sql and display it as console.log(results) it works but not for multiple queries.
var express = require('express');
var app = express();
let mysql = require('mysql')
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'pitch_perfect_db2',
multipleStatements: true
})
app.get('/',(req, res) => {
connection.connect();
var sql = 'SELECT * FROM investors?; SELECT * FROM member_info?;'
connection.query(sql, function(err, results, fields){
if (!err) {
// res.send(JSON.stringify(results[0]));
// res.send(JSON.stringify(results[1]));
console.log('hey');
//console.log(results);
console.log(results[0]);
console.log(results[1]);
} else{
console.log('Error while performing query.');
}
});
connection.end();
})
//app.listen(port, () => console.log('Server Started pn port ${port}'));
app.listen(3002);
I was able to get it to work but I had to do 2 things:
First I renamed the tables to remove the question mark as it was always getting translated to a '1' and the table name no longer matched what was in the DB.
Second, I added an array to the connection.query(). After that it worked just fine.
More info here
var express = require('express');
var app = express();
let mysql = require('mysql')
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'pitch_perfect_db2',
multipleStatements: true
})
app.get('/',(req, res) => {
connection.connect();
var sql = 'SELECT * FROM investors; SELECT * FROM member_info;';
//var sql = 'SELECT * FROM investors;';
connection.query(sql, [1, 2], function(err, results, fields){
if (!err) {
res.send(JSON.stringify(results[0]) + JSON.stringify(results[1]));
console.log('hey');
//console.log(results);
console.log(results[0]);
console.log(results[1]);
} else{
console.log('Error while performing query.');
console.log(err);
}
});
connection.end();
})
//app.listen(port, () => console.log('Server Started pn port ${port}'));
app.listen(3002);
In node you don't use ; in your sql statements. Assuming both the investors and member_info tables have the same number of columns, you will need to use this:
var sql = 'SELECT * FROM investors UNION ALL SELECT * FROM member_info';
Alternatively, if investors and member_info are unrelated tables, you will need to journey into callback hell to get what you need:
app.get('/',(req, res) => {
connection.connect();
var sql1 = 'SELECT * FROM investors';
var sql2 = 'SELECT * FROM member_info?';
connection.query(sql1, function(err, investors){
if (err) throw err; //you should use this for error handling when in a development environment
console.log(investors); //this should print
connection.query(sql2, function(err, members) {
if (err) throw err;
console.log(members);
res.render('your view', {investors:investors, members:members});
});
});
});
If you decide on the latter approach, I would urge you to reconsider your database layout.
If either of the tables in your examples have a foreign key relation with each other, you should definitely be using some kind of JOIN statement on these tables, instead of a UNION.
I am saving signup value into database using expressjs in Rest api but how can i valuate my fields (name,email,password) so if i save without data then error message related to field should show
Here is my code
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});
var toTime = new Date();
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO users (name, email,password) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.password+"')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
First note: you're code is susceptible to SQL injection. Refer: this SO question
Now, You can just make a validation function which returns booleanand use it before the query like
function validateFunc(...params){
return params.reduce((p,c)=> p && (c !== null && c !== undefined), true);
}
And use it like,
if(!validateFunc(req.body.name, req.body.email, req.body.password)){
// throw some error
}
var sql = "INSERT INTO users (name, email,password) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.password+"')";
I am using node-mysql for the first time, and I have a program with no errors, no warnings, but is not working properly... Here is the code for the program, very simple:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database: 'nodetest',
port: 8080
});
connection.connect();
var usr = "BLASHDASD"
var userId = usr;
var sql = 'UPDATE userlist SET user1= ' + connection.escape(userId) + ' WHERE id=1 ';
console.log(sql);
connection.query('sql', function(err, rows, fields) {
console.log(err);
console.log("BLAHSDBKASD");
});
connection.end();
And here is the console output:
C:\wamp\www\nodePHP-master\js>node nodeTest.js
UPDATE userlist SET user1= 'BLASHDASD' WHERE id=1
But nothing is happening in my MySQL table... I even copied and pasted the UPDATE line above and just ran it as SQL code and it worked great... Need some ideas of what is going on. Thanks a bunch
EDIT:
Answered my own question... was listening on wrong port, so connection was failing. Here is updated code for those interested/search in the future:
//TEST
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database: 'nodetest',
port: 3306,
});
connection.connect(function(err){
if(err) {
console.log(err)
} else {
console.log("connected");
}
});
var usr = "BLASHDASD"
var userId = usr;
var sql = 'UPDATE userlist SET user1= ' + connection.escape(userId) + ' WHERE id=1 ';
console.log(sql);
connection.query(sql, function(err, rows, fields) {
console.log(err);
});
connection.end();
You are having problems with node's asynchronous nature, a very common issue when coming to Node. You also had a small but significant error in your code (you have 'sql' as a quoted string), but here is something structurally similar that should point you in the right direction.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'locahost',
user : 'foo',
password : 'bar',
database : 'test'
});
// the callback inside connect is called when the connection is good
connection.connect(function(err){
var sql = "select 'Joe' as name from dual";
connection.query(sql, function(err, rows, fields) {
if (err) return console.log(err);
// you need to end your connection inside here.
connection.end();
console.log(rows[0].name);
});
});
You will likely start wondering about ways to avoid all these callbacks. You may wish to look at my answer to this question for a more extended mysql example as well as an alternative implementation which offers an alternative to callback-mania.
I am trying to connect to a db on my hosting and write out the result, I am not getting any error, just blank space. line like console.log('test'); put at any place always work but I am not getting any query results, what am I doing wrong?
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'wm51.wedos.net',
user : 'xxxxxx',
password : 'xxxxxx',
database: 'd57283_vs'
});
connection.connect();
var queryString = 'SELECT * FROM versus LIMIT 5';
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
console.log(rows[i].title);
}
});
connection.end();
(The table is called versus, has columns title, url...in adminer it's all accessible and the query works...)
Be careful with that connection.end(); call at the bottom. NodeJS is asynchronous, remember?
Try putting that at the end of the inner function after the for-loop, otherwise it will get called as soon as the query is called, possibly killing the connection you're trying to use!
perhaps mysql-server is not to be connected, when you query,or mysql-server is to be closed when you query.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'wm51.wedos.net',
user : 'xxxxxx',
password : 'xxxxxx',
database: 'd57283_vs'
});
connection.connect();
process.nextTick(function() {
var queryString = 'SELECT * FROM versus LIMIT 5';
connection.query(queryString, function(err, rows, fields) {
connection.end();
if (err) throw err;
for (var i in rows) {
console.log(rows[i].title);
}
});
});
I believe the connection.end() statement still needs to be after the for loop. Or else your ending the connection before the loop even starts.
I use the following code using mysql with Node.js
var mysql = require('mysql');
var db = mysql.createConnection({host:'localhost', user:'root', password: 'pw', database: 'db'});
db.connect();
And, I use this to SELECT data and handle error.
db.query("SELECT * FROM user_info WHERE uid = ? LIMIT 1", [selfid], function(err, rows, fields) {
if (err) throw err;
// do something....
});
But, I want to ask that when I use "INSERT" and some error happens, will the app.js crash if I haven't handle error?
var qstr = "INSERT INTO user_info (uid, message, created_time) VALUES(?, ?, CURRENT_TIMESTAMP)";
db.query(qstr, [uid, message]);
No, the app will not crash if you do not handle your errors. It will continue silently. It is up to you to catch the errors and handle them.
var qstr = "INSERT INTO user_info syntax error";
db.query(qstr, function(err) {
if (err) {
console.log("A wild error appeared!", err);
process.exit(1);
}
});