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);
});
});
Related
I want to return the result of query to DB, which I think would be a promise and then consume that promise in another file.Here is my model code (User.js) :
User.prototype.login = function () {
return new Promise((resolve, reject) => {
pool.execute('SELECT * FROM `users` WHERE `username` = ? AND `password` = ?', [this.data.username, this.data.password], (err, attemptedUser) => {
if (err) {
pool.release();
return reject(err);
} else {
pool.release();
return resolve(attemptedUser);
}
});
});
}
and the code in my controller file (userController.js):
const User = require('../models/User');
exports.login = (req, res) => {
let user = new User(req.body);
user.login()
.then((result) => {
res.send(result);
})
.catch((err) => {
res.send(err);
});
};
But when I click on the login button the page doesn't go to the specified URL and keeps working until crash.
Where is the problem?
UPDATE-1
This is my db.js :
const mysql = require('mysql2/promise');
const dotenv = require('dotenv');
dotenv.config();
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
connectionLimit: 100
});
module.exports = pool;
I have been doing google searches for 5 days, I hope to find the solution ... I know that it does not work because it is asynchronous, but I need the program (it is a Discord bot) to respond with a data that I get from a DB. I have tried Promises and callbacks, but I do not know if it is because I am a novice with asynchronous, that nothing works for me.
const con = mysql.createConnection({
host: datos.host,
user: datos.user,
password: datos.password,
database: datos.database
});
function leerPromesa() {
var promise = new Promise(function (resolve, reject) {
con.query('SELECT * from ranking;', function (err, rows, fields) {
if (err) {
reject(err);
return
}
resolve(rows);
rows.forEach(element => console.log(element));
})
});
return promise;
};
var promesa = leerPromesa();
promesa.then(
function (rows) {
rows.forEach(element => msg.reply(element));
},
function (err) {
msg.reply(err);
}
);
con.end();
What the bot does is respond with blank text.
First, you're not really connecting to database.
If you refer to docs https://github.com/mysqljs/mysql:
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
// then connect method
connection.connect();
So your code will never work..
Second, you are closing connection before any query execution:
con.end();
Correct is to close connection after leerPromesa function execution.
Finally, code could look something like this:
const con = mysql.createConnection({
host: datos.host,
user: datos.user,
password: datos.password,
database: datos.database
});
con.connect();
function leerPromesa() {
return new Promise(function(resolve, reject) {
con.query("SELECT * from ranking;", function(err, rows, fields) {
if (err) {
return reject(err);
}
return resolve(rows);
});
});
}
leerPromesa()
.then(
function(rows) {
rows.forEach(element => msg.reply(element));
},
function(err) {
msg.reply(err);
}
)
.finally(function() {
con.end();
});
I used finally method on Promise to close connection in every situation https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
My code have an obj name SQLFeeter that need to do the sql interaction which get the data post it and pass it along I have some problem which is one imports. The babel doesn't work second while I try to get the data and pass it
const express = require('express');
const router = express.Router();
const mysql = require('mysql')
/*
--------------------------------------
This will handel all get requests
--------------------------------------
*/
/*
//sqlInteractuin test
const SqlDataGetter = require('../../sqlInteraction/GetData');
//import SqlDataGetter from "./sqlInteraction/GetData";
let SqlGetter = new SqlDataGetter
*/
class SqlDataGetter {
constructor()
{
this.con = mysql.createConnection({
host: "localhost",
user: "XXX",
password: "XXX",
database: "APP"
});
}
GetClients()
{
let con = mysql.createConnection({
host: "localhost",
user: "XXX",
password: "AAA",
database: "APP"
});
let resultFromSql = null;
con.connect(function(err) {
if (err) throw err;
let sql_query = "SELECT * FROM contacts"
con.query(sql_query , function (err, result, fields) {
if (err) throw err;
//console.log(fields);
console.log(result);
resultFromSql = result;
});
return resultFromSql;
});
}
Tester()
{
//return this.con
//console.log(this.con)
return 'hello world'
}
}
router.get('/' , async (req , res) =>
{
//Need to make an obj that take the data and do all the querys
res.status(200).send("DataBack");
});
router.get('/Clients' , async (req , res) =>
{
let sql_getter = new SqlDataGetter();
const Clients = sql_getter.GetClients();
console.log(Clients);
SqlDataGetter.GetClients()
res.status(200);
res.send({ respond : Clients});
});
While I am trying to run this at first it works on stand alone but when I create the ajax request it saying GetClients is not a function. And when I try to make the connection to be a property of this object as this.con when I activate this.con.query undifend property query of undifend.
If you use promise-mysql instead of mysql then you'll get promises from the method calls, which will make it easier to work with:
const mysql = require('promise-mysql');
Then your class would look like this:
class SqlDataGetter {
constructor() {
this.conPromise = mysql.createConnection({
host: "localhost",
user: "XXX",
password: "XXX",
database: "APP"
});
}
async GetClients() {
const con = await this.conPromise;
const result = await con.query("SELECT * FROM contacts");
console.log(result);
return result;
}
}
Finally, you'd use that class as follows:
router.get('/Clients' , async (req , res) => {
let sql_getter = new SqlDataGetter();
const clients = await sql_getter.GetClients();
console.log(clients);
res.status(200);
res.send({ respond : clients});
});
I have a node mysql connection that used to work properly but since traffic started coming i am getting a strange error
Error: Connection lost: The server closed the connection.
This is the class that i'm using
const mysql = require('mysql');
class Database {
constructor() {
this.connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: 3306,
debug: false,
multipleStatements: false
});
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.connection.query(sql, args, (err, rows) => {
if (err)
return reject(err);
resolve(rows);
});
});
}
close() {
return new Promise((resolve, reject) => {
this.connection.end(err => {
if (err)
return reject(err);
resolve();
});
});
}
}
module.exports = Database;
Can someone help as to why this is happening?
Edit: this is how i call the code
const database = new Database();
database.query(`select * from users...
`, [req.user.id, parseInt(req.body.after)])
.then(rows => {
appData[".."] = rows['ddd']
res.status(200).json(appData);
database.close()
}, err => {
return database.close().then(() => { throw err; })
})
.catch(err => {
console.log(err);
res.status(500).json("Database Error");
})
first create file ex database.js
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: conf_core_sys.dbConfig.host,
user: conf_core_sys.dbConfig.user,
dateStrings: true,
password: conf_core_sys.dbConfig.pass,
database: conf_core_sys.dbConfig.dbName,
port:conf_core_sys.dbConfig.port,
debug: false
});
module.exports = pool;
exports.executeQuery = function (query, callback) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
throw err;
}
connection.query(query, function (err, rows) {
connection.release();
if (!err) {
callback(null, {
rows: rows
});
}
});
connection.on('error', function (err) {
throw err;
return;
});
});
}
second step :
let database = require("database")
let sql ="SELECT * from users";
database.query(sql, function (error, results, fields) {
if (error) {
callback(results)
} else {
callback(results)
}
})
some time ago i had the same problem, but at this time the probelm has not happened, maybe this solution helping you,
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: 3306,
debug: false,
multipleStatements: false
});
module.exports = pool;
exports.executeQuery = function (query, callback) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
throw err;
}
connection.query(query, function (err, rows) {
connection.release();
if (!err) {
callback(null, {
rows: rows
});
}
});
connection.on('error', function (err) {
throw err;
return;
});
});
}
I'm trying to get data from my DB and use it in different modules of my app. My app is split in a lot of modules which I require where I need them.
My connectDB.js module looks like this
var mysql = require('mysql');
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "pw",
database : "something"
});
db.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Database connected');
});
function select(query)
{
db.query(query,function(err,rows){
if(err) throw err;
return rows;
});
}
module.exports =
{
select
}
I was hoping to simply just require this module and then do a something like
db.select('SELECT * FROM users');
But for some reason the return value is always "undefined"
Sending queries inside the connectDB module works as expected returning the correct data. But I can't use my function to get data.
Is there something wrong here with my logic? Can you help what I am doing wrong?
As I remember, connection.query will return result async, so you need to wrap it with callback or Promise.
var mysql = require('mysql');
function DB {
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "pw",
database : "something"
});
db.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Database connected');
});
this.select = function(query, callback) {
db.query(query,function(err,rows){
if(err) throw err;
callback(rows);
});
}
//Promise version
this.selectPromise = function(query) {
return new Promise(function(resolve, reject){
db.query(query,function(err,rows){
if(err) reject(err);
resolve(rows);
});
});
}
}
module.exports = DB;
How to use:
var DB = require('your-module');
var db = new DB();
db.query('select * from table', function(result) {
console.log(result);
});
db.selectPromise('select * from table').then(function(result) {
console.log(result);
});
Make the following change to your code
module.exports =
{
select: select
}
And you forgot about callback function
function select(query, callback)
{
db.query(query,function(err,rows){
if(err) throw err;
return callback(rows);
});
}
Then you can pass a function like this:
db.select('SELECT * FROM users', function(rows) {
// Do stuff with rows
});