What does connection.connect() do in node-mysql? - mysql

What does the connection.connect() do in node-mysql library?
My code looks like this
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'ap-cdbr-azure-east-a.cloudapp.net',
user : '<user>',
password : '<password>',
database : '<database>',
});
connection.connect();
Later I run the query.
Even if I remove connection.connect() the code works as is. Some examples have it, some don't. What is the specific purpose for connect() ?

The recommended way to establish a connection is this:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function(err) {
// connected! (unless `err` is set)
});
However, a connection can also be implicitly established by invoking a query:
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function(err, rows) {
// connected! (unless `err` is set)
});
Depending on how you like to handle your errors, either method may be appropriate. Any type of connection error (handshake or network) is considered a fatal error.
Courtesy: https://github.com/felixge/node-mysql

Related

How to make a request in a localhost mysql database

I am using mysql and request. I want to make a request in my localhost server. I just need to know how to make the get request into the localhost server because I don't understand how, I'm running into a continuous loop.
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'virtual_currency_price'
});
Request:
router.get('/getprice', function(req, res){
request(connection, function (error, response, body) {
if (!error && response.statusCode == 200){
}
});
});
I'm trying to figure out how to do this but I'm failing very miserably
The table I'm trying to GET from is called "price" and I will be using the datetime to fetch certain prices.
After you establish a connection with your server you can use it to fetch data from database. You don't need to make a request using the module, just use the connection directly to execute queries as below:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'virtual_currency_price'
});
connection.connect();
connection.query('SELECT * from price', function(err, rows, fields) {
if (err) throw err;
console.log(rows);
});
connection.end();
It's recommended that you create a pool of connections instead and reuse them in your app instead of creating it every time you need to access the DB.
See the docs from github.

Nodejs (Express) connecting MySQL - Local and Remote connection different?

guys. I am learning how to use Express to connect to remote MySQL. So, I started out doing it on my local machine (a local MySQL server). After I have succeeded on the local environment, I tried changing the the connection to a remote MySQL hosting (at DB4Free). Yes, I have succeeded on the localhost. However, whenever I run a Get/Post to the remote MySQL Server, my console show me the error below. I'll attach the related segment of codes below here. I have been trying it the whole afternoon.
Hope that someone here can enlighten on this matter. Thank you in advance guys :)
This is the error shown in my console
My file for connecting db is as below - ConnectionString.js
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit : 100,
host : '85.10.205.173:3306',
user : '******* ',
password : '*******',
database : '*******',
});
exports.getConnection = function(callback) {
pool.getConnection(function(err, conn) {
if(err) {
return callback(err);
}
callback(err, conn);
});
};
Portion of my file for the routes and query is this
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var conn = require('../database/ConnectionString');
var result;
//Validate user login
router.get('/login', function(req, res, next) {
conn.getConnection(
function (err, client) {
client.query('SELECT * FROM mt_User', function(err, rows) {
// And done with the connection.
if(err){
console.log('Query Error');
}
res.json(rows);
client.release();
// Don't use the connection here, it has been returned to the pool.
});
});
});
Alright, I have found the issue. It seems that the mysql package in npm requires that the host and port to be defined separately. After tuning it to this code below for my ConnectionString.js file. It finally works.
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit : 100,
host : '85.10.205.173',
port : 3306,
user : '*******',
password : '*******',
database : '*******',
});
exports.getConnection = function(callback) {
pool.getConnection(function(err, conn) {
if(err) {
return callback(err);
}
callback(err, conn);
});
};

NodeJS MySQL - How to know connection is release or not

I am developing NodeJS + MySQL web API.
I am using mysql npm module.
I want know connection is release or not is there any function or variable.
Like
if(!connection.isRelease() OR !connection.isClose() OR !connection.end()) {
connection.release();
}
Is there any specific function to know connection is release or not?
I am getting error like "connection already release"
You can check if the connection is in the pool to see if it was released. The index in the free connections will be -1 if the connection is not released. Here is an example.
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : ''
});
pool.getConnection(function(err, connection) {
connection.query( 'SELECT something FROM sometable', function(err, rows) {
console.log(pool._freeConnections.indexOf(connection)); // -1
connection.release();
console.log(pool._freeConnections.indexOf(connection)); // 0
});
});
Just in case you don't have access to the pool you can also do this:
connection._pool._freeConnections.indexOf(connection)
This will give you the same answer as the accepted answer.

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 changes in mysql

i have a question regarding about node.js for mysql.
I'm trying to check for changes in the database with node.js and every time it does a change it would do something.
I have the following code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'socialpodd',
});
connection.connect();
connection.query('SELECT * FROM personal', function(err, rows, fields) {
if (err) throw err;
console.log('Rows: ', rows[0].email);
});
connection.end();
But I want this code to be called once there is a change in the database. I know I could do a poll method, but it doesn't seem that effective and real-time. What would be a good real-time module that would allow me to do it, or is polling my only option?