Electron MySQL Variable Scope - mysql

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>

Related

How to return a JSON object from a mySQL query in node.js

I'm very new to coding and node.js in particular so this is probably a dumb question - but all the examples I read for mySQL database queries end with just logging the query results to the console... what I want to do (or at least what I think I want to do) for my web application is return the query result as the product of a function so that I can allow my .ejs file to make use of the JSON object.
The situation as the moment is no matter what I try my .ejs file receives "Hello World" as the product of getDriver(). I want it to receive 'rows' (ie. the JSON object that my SQL query returns with)
I can see the JSON result in the console & it looks perfect.. I just can't seem to make it 'exist' outside of the function :(
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
/* GET about page. */
router.get('/', function(req, res, next) {
res.render('SQLtest', { title: 'SQL test',
result: getDriver() // I want this to be my JSON object
});
});
module.exports = router;
function getDriver() {
var result = "Hello World"; // my .ejs see's this
var connection = mysql.createConnection(
{
host: 'localhost',
user: 'root',
password: 'password',
database: 'my database',
port: 3306
}
);
connection.query("SELECT * FROM my_table",
function (err, rows) {
if (err) {
console.log(err);
}
console.log(rows); // query result looks fine as JSON object
result = rows; // now change "Hello World" to the JSON object
}
);
return result; // however this still = "Hello World" :(
}
The database query is an asynchronous call - this means that the return result statement may execute BEFORE the query results are returned and the value of result is updated via result = rows.
What you need to do is to introduce a callback function as a parameter in your getDriver function. Your code will then look like this (I moved the database connection code out of the getDriver function):
//You should move this out of the function - you want to set it once
var connection = mysql.createConnection(
{ host: 'localhost',
user: 'root',
password: 'password',
database: 'my database',
port: 3306
});
function getDriver(callback) {
connection.query("SELECT * FROM my_table",
function (err, rows) {
//here we return the results of the query
callback(err, rows);
}
);
}
This is how you now call the getDriver function:
router.get('/', function(req, res, next) {
//now you can call the get-driver, passing a callback function
getDriver(function (err, driverResult){
//you might want to do something is err is not null...
res.render('SQLtest', { 'title': 'SQL test',
'result': driverResult});
});
});
Give it a try and let me know if it works.
I hope this helps.

Node.js returning partially duplicate row from MySQL

I'm new to Node.js and "asynchronous land" and have met some strange problems.
Things I intended to do:
Node.js query from MySQL
What was the problem:
the row query from Node.js got partially duplicate columns.
e.g. Here's the result by looking up the MySQL directly, please notice the userId:
user1 is ending with 36 and user2 is ending with 37
and here's the output from Node.js
I've got user1 and user2 with same userId, although other columns are correct.
Code:
I created the table userInfo using the following:
create table userInfo(userId bigint, userName text, userEmail text, userNetwork text, userAvatar blob);
and populate it using:
insert into userInfo values(uuid_short(), 'user1', 'user#test.com', 'facebook', null);
insert into userInfo values(uuid_short(), 'user2', 'user2#test.com', 'facebook', null);
The Node.js code I'm using:
var http = require("http"),
// And url module, which is very helpful in parsing request parameters.
url = require("url"),
// add sql module
mysql = require("mysql");
var connection = mysql.createConnection({
host: 'localhost',
user: "root",
password: "xxxxxx",
database: "db"
})
// show message at console
console.log('Node.js server is running.');
// Create the server.
http.createServer(function (request, response) {
request.resume();
// Attach listener on end event.
request.on("end", function () {
// Parse the request for arguments and store them in _get variable.
// This function parses the url from request and returns object representation.
var _get = url.parse(request.url, true).query;
// query the database
connection.connect();
var getInfo = _get['getInfo'];
var qString = new Buffer(getInfo, 'base64').toString('utf8');
console.log(qString);
connection.query(qString, function (error, rows, fields) {
if (error) {
throw error;
}
if (rows.length > 0) {
// send the data as json
console.log(JSON.stringify(rows));
response.end(JSON.stringify(rows));
} else {
// send code 200 json as there are no rows
response.end(JSON.stringify({code:200}));
}
});
});
}).listen(8080);
This problem persists even I've replaced this
connection.query(qString, function (error, rows, fields)
into
connection.query('SELECT * FROM userId', function (error, rows, fields)
Could you tell me where I'm heading wrong?
I guess the problem is I'm not coping well with asynchronous?
UPDATE
I tried the same SQL and code on another machine(windows machine) and the result are the same, with every other columns correct but the userId:
Query from MySQL:
Query using Node.js:
After this test, I thought about the problem may come from the Big Int that JSON cannot handle correctly. Thus I switched all my output using json-bigint, however, the problem still not get resolved:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "",
password: "",
database: ""
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO studentdetails(fname,lname,age,dob,streetname,city,state,pincode) VALUES ('aaa','bbb',22,'1994-05-13','PC','MTM','qqqq',1242352)";
**con.query(sql, function (err,rows,result) {
if (err) throw err;
if (rows.fname === sql.fname) {
console.log('Already exist');
}
else {
console.log("1 record inserted");
}**
con.end();
});
});
// is this correct to ignore the duplicate values??
suggest me an answer please
Set bigNumberStrings driver connection option to true, that way big numbers are serialised in result as a string:
var connection = mysql.createConnection({
host: 'localhost',
user: "root",
password: "xxxxxx",
database: "db",
supportBigNumbers: true,
bigNumberStrings: true
})
Bigint-s will always be a pain in Javascript. You can try to hack your way around it, but why bother?
Two possible solutions:
1) Use smaller integers that don’t cross the threshold where their encoding in Javascript breaks, or
2) Use some other data type, such as string.
The magnitude of the integers is the problem, as others have pointed out. Here are some additional bits to think about:
Some brief googling suggests that they're working on standardizing some introspection for this in ES6.
To see the maximum integer you can use in Chrome, open the console and output the value for Number.MAX_SAFE_INTEGER -- you'll see it's less than the value of your userIds. The specific value is due to the limits of Javascript's internal floating-point representation -- beyond a certain size, integers become impossible to precisely express.
Here's a blog post that gets into the details.

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.

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

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.

how to return \ retrieve a result from node.js module that does query to mysql?

I want to pass a result from mysql query to the level above...
I have this module: mySQLconnect.js:
var connection = require('mysql').createConnection({
host : 'localhost',
user : 'admin',
password : ''
});
exports.querySelect = querySelect;
function querySelect(query){
var result = connection.query(query, function(err, rows){
return (rows[0]);
});
return result;
}
and when I call this function from outside, let's say from app.js:
var DBconnector = require('mySQLconnect');
var result = DBconnector.querySelectUser("SELECT * FROM TB_USERS");
but the result I get is something else - it's an object from mysql.js module that's been received from:
connection.query(query, function(err, rows)
it has: _resultSet =null, and unreachable _results =[Array]
so it's no good...
I checked in node-mysql website, but didn't find what's connection.query returns.
any ideas how can I pass the result?
You are wrapping an asynchronous call to the DB with a procedural function – a common mistake for nodejs beginners coming from a procedural language like PHP.
You can simplify your mySQLconnect.js module to the following:
var connection = require('mysql').createConnection({
host : 'localhost',
user : 'admin',
password : ''
});
exports.querySelect = connection.query;
And then consume it thusly:
var DBconnector = require('mySQLconnect');
DBconnector.querySelect("SELECT * FROM TB_USERS", function (err, rows) {
console.log(err || rows);
});
I would read up on callbacks, anonymous functions, and asynchronous flow patterns to help you wrap your head around this new style of coding. Good luck!