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.
Related
This happens pretty frequently (once a week for about 30-40 minutes), where all of a sudden my database mentions max connections when I try to connect via heidisql, and any apis calls respond with the following error:
Cannot read property 'release' of undefined
I am calling .release() after every query in mysql. Is there something I am missing, am I suppose to call .end as well? I am using nodejs with mysql.
Here is the way I wrap every query and the pool code:
var mysql = require('mysql');
var mysql_pool = mysql.createPool({
connectionLimit: config.mysql.limit,
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.pw,
database: config.mysql.db //,
// debug: true
});
var qSelect = "SELECT id FROM Users";
var qValues = [];
var qCall = mysql.format(qSelect, qValues);
mysql_pool.getConnection(function(err_pool, connection) {
if (err_pool) {
connection.release();
console.log(' Error getting mysql_pool connection: ' + err_pool);
throw err_pool;
}
connection.query(qCall, function(err, userFound, fields) {
connection.release();
if (err) {
console.log("get user : " + err);
} else {
//some code here
}
});
Can someone please advise, appreciate it.
You should remove first connection.release() used in if loop
if (err_pool) {
console.log(' Error getting mysql_pool connection: ' + err_pool);
throw err_pool;
}
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 using mysql with Electron.
Here is my code to connect to database. I am in a problem of variable scope. I do google for a long time but found no solution.
What I want to do is described within the uppercase comment inside the code. Please look at the code and give me suggestion if any.
<script>
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: null,
database: 'electron_db'
});
connection.connect();
var sql = 'SELECT `emp_id`,`emp_name` FROM `employee`';
connection.query(sql, function(error, results, fields) {
if (error) console.log(error.code);
else {
console.log(results);
$('#resultDiv').text(results[0].emp_name); //emp_name is column name in your database
// I WANT TO ASSIGN emp_name TO A VARIABLE x AND TO USE IT OUTSIDE THE CALLBACK.
// LIKE THIS
// ASSIGN VARIABLE HERE
x = results[0].emp_name;
}
});
connection.end();
// USE VARIABLE x HERE
$('#resultDiv').text(x);
</script>
I'm getting below error while fetching records (apx 50 rows) from my sql database. My application is developed in nodejs with express.
var common = require(__base + 'routes/common.js');
var dbhelper = require(__base + 'routes/dbhelper.js');
exports.GetStates = function (callback) {
dbhelper.pool.getConnection(function (err, connection) {
// Use the connection
connection.query('CALL GetStates()',
function (err, res) {
connection.release();
if (err) {
common.ActionOutput.Status = common.ActionStatus.Error;
common.ActionOutput.Message = 'System Error: ' + err.message;
} else {
common.ActionOutput.Status = common.ActionStatus.Success;
common.ActionOutput.Result = res[0][0];
}
return callback(JSON.stringify(common.ActionOutput));
});
});
};
dbhelper.js is
// Database connection
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: 'my ip',
user: 'user',
password: 'pass',,
database: 'ssdsdas'
});
exports.pool = pool;
I ran into the same error message but the causes of our issues might be different. Ultimately, the cause of my issue is that the column names in my stored procedure did not have back ticks (`) resulting in them being treated as variables.
Adding back ticks in my stored procedure body for column names fixed it.
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.