How to query with node-mysql and write out the results? - mysql

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.

Related

I want my query result to be displayed in format of actual table Node.js HTML CSS

I am building a project for Database Course.
I am already done with Front End. I built the front end using Tailwind CSS.
Now I've started working on the backend and getting data from the database and display on my website using Node.js
I am a beginner and I want the result of the query to be styled and formatted like an actual table.
So I need help as I didn't find a reliable solution on the internet
I AM ATTACHING THE OUTPUT RESULT AND THE KIND OF RESULT I WANT.
Here is my Node.js code
var mysql = require('mysql');
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345678",
database: "mydb"
});
var sqlQuery = "SELECT username FROM Users";
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
// con.query(sqlQuery, function (err, result) {
// if (err) throw err;
// console.log(result);
// });
});
// display query result on host
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
// display query result on host
con.query(sqlQuery, function (err, result) {
if (err) throw err;
//show result in table format
res.end(JSON.stringify(result));
});
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
CURRENT OUTPUT
OUTPUT I WANT

How do I avoid max connections error in mysql?

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;
}

No hint of errors when trying to connect to a database

I've been struggling to get MySQL working with node for a while. When I run the following code no errors are thrown, but simultaneously none of the console messages are being printed (except for the obvious one).
var app = require('express')();
var http = require('http').Server(app);
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '******',
database : 'blogDB'
});
connection.connect(function(err) {
if(err) {
console.log('error when connecting to database:', err);
}
console.log('Connected to the database');
});
var queryString = 'SELECT * FROM blogs';
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
console.log('Post: ', rows[i].id);
}
});
connection.end();
http.listen(3306, function(){
console.log('listening on *:3306');
});
Output:listening on *:3306
On top of this, when I go to "localhost:3306" in the browser, a download is immediately started and nothing appears on the web page. The download is a file with no extensions, but contained the following:
J
5.6.19 tscvKP3M ÿ÷ € g?F!q6X:Y2*z mysql_native_password ! ÿ„#08S01Got packets out of order
I am not sure if that is relevant, but it certainly was not happening when I was not running MySQL. I have no idea how to troubleshoot this. Any ideas what could be going wrong?
The error here is you're coding node.js as if it were procedural. It's not.
connection.connect(function(err) {
if(err) {
console.log('error when connecting to database:', err);
}
console.log('Connected to the database');
var queryString = 'SELECT * FROM blogs';
//change from connection to "this" because you're inside the context of the connection object now
this.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
console.log('Post Titles: ', rows[i].id);
}
});
});
Node.js uses a series of callbacks that run when a task is completed. So when you want to do something AFTER you're connected to the DB, you run that code inside the callback.
What your code is doing is attempting to connect to the database, then while attempting to connect to the database you're querying a database you're not connected to, and so on and so forth.
For sake of illustrating the principle a little more, node functions use the following general methodology.
//1
myObj.myFunc( function( err , foo , bar ) {
//A
});
//2
myObj.myOtherFunc( function( err , someVar ) {
//B
});
1 will always run before 2. A and B may run in either order depending on when 1 and 2 finish executing. A will always run after 1 is done. B will always run after 2 is done.
Hopefully that helps clear things up ;)
As it turns out, MySQL and the app were running using the same port (3306). Changing the app's port to 3307 did the trick.

Node-mysql not working properly... need debug ideas

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.

Node.js http with mysql pooling quits unexpectedly on error

So I started to try node.js this morning and was able to come-up with a http service that handles path requests and can connect to mysql with pooling for multiple transactions.
I am just having problems if ever I tried to make the password wrong, etc the node process quits unexpectedly.
var http = require("http");
var url = require("url");
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : 'root',
database : 'test'
});
...
var pathname = url.parse(request.url).pathname;
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
...
var table = query.table;
var sql = "SELECT * FROM " + table + "";
...
pool.getConnection(function(err, connection) {
console.log(err);
connection.on('error', function(err) {
console.log(err.code);
});
// Use the connection
connection.query(sql, function(err, rows) {
if (err) throw err;
console.log(rows);
response.writeHead(200, {
"Content-Type" : "application/json"
});
response.write(JSON.stringify(rows, null, 0));
connection.end();
response.end();
});
console.log(connection.sql);
console.log(connection.query);
});
Appreciate any help on how can I make it not to QUIT! and just say the damn error.
Anyway, I used forever to make this node.js to never quit on me, in-cases of error.
You use throw err, but don t catch it anywhere, causing node a UncaughtException Error, closing the app.