W3School tutorial on NodeJs-MySQL: SELECT cmmand does not provide output in proper format. In each row of output "RowDataPacket" word is appearing. How to avoid it?
C:\Users\Raju>node demo_db_select.js
[ RowDataPacket { id: 1, name: 'John', address: 'Highway 71' },
RowDataPacket { id: 2, name: 'Peter', address: 'Lowstreet 4' },
I used the following code:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
var data = [
RowDataPacket { id: 1, name: 'John', address: 'Highway 71' },
RowDataPacket { id: 2, name: 'Peter', address: 'Lowstreet 4' }
]
This means the inside object is the instane of the class RowDataPacket. You can still simply use it like:
data[0].id // 1
data[0].name // John
data[1].name // Peter
You are executing a MySQL query and storing the selected rows and columns in result variable. Actually result is a object. So run a for loop and print all the values as I written in code.
Try this code:
var mysql = require('mysql');
var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword", database: "mydb" });
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
for(let i in result){
console.log("id="+result[i].id);
console.log("Name="+result[i].name);
console.log("address="+result[i].address);
}
});
});
Related
I'm currently writing an app where I am querying my MySQL database table that has three rows. I want to save each of the rows as a variable/string.
E.g SELECT * FROM orders LIMIT 1 where the response is
[
RowDataPacket {
orderid: 1,
email: 'isadg232323fskdjghfjkhbdfkjhsdf#gmail.com',
token: 'ABCDEF4TZX1A9G7Z'
}
]
How do I extract the email from the result and set it as a variable such as "email" for future use in my app.
My current code:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "123.456.123.456",
user: "user",
password: "pass",
database: "db"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM orders LIMIT 1", function (err, result, fields) {
if (err) throw err;
console.log(result);
con.end();
});
});
The answer was very simple. Thanks Asad! I was missing the array position when I tried to do result.email.
Solution is
email = result[0].email; assuming I want the email.
This is how my code looks like:
var con = mysql.createPool({
connectionLimit : 10,
host: 'X.X.X.X',
user: 'abcd',
password: '1234',
database: 'basic'
});
con.query('INSERT INTO tbasic SET ?', data, (err, ret) => {
if(err) {
res.status(200).json({
response_code:500,
message:'Error inserting data!',
data:err
});
}
else {
console.log('Last insert ID:', ret);
res.status(200).json({
response_code:200,
message:'ok',
data:ret
});
}
});
Whenever this application runs, after a while I get Too many connections error on the DB.
I know about the possible duplication issue but I have tried almost all solutions I found so far. None of them seems to work. What am I missing here?
Try using the long-handed way of pooling connections
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host: 'X.X.X.X',
user: 'abcd',
password: '1234',
database: 'basic'
});
pool.getConnection(function(err, connection) {
if (err) throw err; // No connection
connection.query('INSERT INTO tbasic SET ?', function(error, ret) {
if(error) {
res.status(200).json({
response_code:500,
message:'Error inserting data!',
data:error
});
} else {
console.log('Last insert ID:', ret);
res.status(200).json({
response_code:200,
message:'ok',
data:ret
});
}
// Release current connection
connection.release();
// Handle error after connection released
if (error) throw error;
});
});
I made this:
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
async function query(query) {
const result = await pool.query(query)
return result[0]
}
console.log(query('SELECT * FROM `users`'))
and I got back
Promise { <pending> }
How do I get back my results from querying the database, just like PHP can do?
In PHP I never had to do such a thing like async/await and promises...
I also tried using mysql:
const mysql = require('mysql')
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodejs'
})
function query(query) {
db.query(query, (err, result) => {
if (err) throw err
return result
})
}
console.log(query('SELECT * FROM `users`'))
but I got an undefined result
try this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
// function definition
function runQuery (con, sqlQuery) {
return new Promise((resolve, reject) => {
console.log("START");
if(con){
con.connect(function (err) {
if (err) throw err;
});
if (sqlQuery) {
con.query(sqlQuery, function (error, result, fields) {
connection.end(); // end connection
if (error) {
throw error;
} else {
return resolve(result);
}
});
} else {
connection.end(); // end connection
// code: handle the case
}
} else {
// code: handle the case
}
});
}
var sqlQuery = 'SELECT * FROM tableName';
// function call and pass the connection and sql query you want to execute
var p = runQuery(con, sqlQuery);
p.then((data)=>{ // promise and callback function
console.log('data :', data); // result
console.log("END");
});
I am not very familiar with MySQL and the libraries that you are using.
However, the Promise { <pending> } response that you are getting is because you didn't await your query execution.
Since the function is marked as async and is also performing an async action, it returns a Promise that needs to be awaited to be resolved.
The code below should work:
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
async function query(query) {
const result = await pool.query(query)
return result[0]
}
(async () => {
const queryResult = await query('SELECT * FROM `users`');
console.log(queryResult);
} )();
To understand how async-await works, consider the code below:
console.log('I will get printed first');
const asyncFunction = async () => {
await setTimeout(()=> {}, 1000)
console.log('I will get printed third');
return 'hello'
}
(async () => {
const result = await asyncFunction();
console.log(`I will get printed last with result: ${result}`);
})();
console.log('I will get printed second');
The console.log statement I will get printed last with result will wait for the asyncFunction to complete execution before getting executed.
Try this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Problem:
I have created a node application there I am adding admin to the database like this in userModal.js file.
var bcrypt = require('bcryptjs');
var sql = require('../db.js');
module.exports.save_admin = (new_admin,callback) =>{
bcrypt.genSalt(10,(err, salt)=> {
bcrypt.hash(new_admin.password, salt, (err, hash)=> {
new_admin.password = hash;
if(err){
throw err;
}
else{
console.log(new_admin.password);
sql.query("INSERT INTO administrators set ?", new_admin, callback);
}
});
});
}
This is how I am calling this function from the controller.
var admin = {
first_name: req.body.first_name,
last_name: req.body.last_name,
organization: req.body.organization,
admin_level: req.body.admin_level,
user_identity: req.body.identity,
username: req.body.username,
password: req.body.password
};
User.save_admin(admin, (err,user) => {
if (!err) {
res.json({ state: true, msg: "data Inserted" });
} else {
res.json({ state: false, msg: "data Is Not Inserted" });
}
});
This is how I have configured the database in db.js file.
'user strict';
var mysql = require('mysql');
//local mysql db connection
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'mydatabase'
});
connection.connect(function(err) {
if (!err){
console.log("Database connection succeeded...!");
}
else{
console.log('Error in DB connection :'+JSON.stringify(err,undefined, 2));
}
});
module.exports = connection;
module.exports = {
"secret": "myapplicationsecret"
};
This setup leaves me this error.
sql.query("INSERT INTO administrators set ?", new_admin, callback);
^
TypeError: sql.query is not a function
I am very new to nodejs. I am using mysql node module. This is how I use it:
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'sample'
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
var post = {PersonID: 1, Name: 'Prachi', City: 'Blore'};
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});
console.log(query.sql);
This node code works functionally. As in, it adds data to the table. But it doesn't terminate. What is the mistake which I am making?
Take a closer look at the official documentation, you have to close the connection :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
Use connection.end() to close the connection
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
connection.end();
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});