mysql - No hint of errors when trying to connect to a database -



mysql - No hint of errors when trying to connect to a database -

i've been struggling mysql working node while. when run next code no errors thrown, simultaneously none of console messages beingness printed (except 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 database:', err); } console.log('connected database'); }); var querystring = 'select * blogs'; connection.query(querystring, function(err, rows, fields) { if (err) throw err; (var 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 go "localhost:3306" in browser, download started , nil appears on web page. download file no extensions, contained following:

j 5.6.19 tscvkp3m ÿ÷ € g?f!q6x:y2*z mysql_native_password ! ÿ„#08s01got packets out of order

i not sure if relevant, not happening when not running mysql. have no thought how troubleshoot this. ideas going wrong?

the error here you're coding node.js if procedural. it's not.

connection.connect(function(err) { if(err) { console.log('error when connecting database:', err); } console.log('connected database'); var querystring = 'select * blogs'; //change connection "this" because you're within context of connection object this.query(querystring, function(err, rows, fields) { if (err) throw err; (var in rows) { console.log('post titles: ', rows[i].id); } }); });

node.js uses series of callbacks run when task completed. when want after you're connected db, run code within callback.

what code doing attempting connect database, while attempting connect database you're querying database you're not connected to, , on , forth.

for sake of illustrating principle little more, node functions utilize next general methodology.

//1 myobj.myfunc( function( err , foo , bar ) { //a }); //2 myobj.myotherfunc( function( err , somevar ) { //b });

1 run before 2. , b may run in either order depending on when 1 , 2 finish executing. run after 1 done. b run after 2 done.

hopefully helps clear things ;)

mysql node.js express

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -