I am having trouble returning results when running queries on my MySQL database using Node.js. Below is an example of my code, which currently outputs nothing to the console.
const mysql = require("mysql");
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'tl'
});
connection.connect();
connection.query = ('SELECT * from employees', function(error, results, fields) {
if (!error) {
console.log(results);
} else {
throw error;
}
});
connection.end();
Authentication is correct.
The database and table are not empty. Running the same query in MySQL itself returns rows.
The code below will give me 'Connection established':
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
There is nothing wrong with my DB or table, all is working as expected, apart from running these queries. I've followed the official documentation and others
Related
Currently I am playing around with the MySQL library in Node.js however I have a question about the correct/most efficient way to be using this library.
According to w3schools the correct way to make a single query is to use code like 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);
});
});
However, say I wanted to make multiple queries which would be executed by an event for example how would I handle this? Should I create an "initialise" function which is executed as soon as the program runs such as this?
var mysql = require('mysql');
var database;
//Initialise database
function setupDatabase() {
database = mysql.createConnection({
host: token.host,
user: token.user,
password: token.password,
database: token.database,
port: token.port
});
}
//Imagine this could be called at any time after execution
function event() {
if(database != null) {
database.connect(function(err) {
if (err) throw err;
database.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
}
}
And also do I have to connect to the database each time I make a query or can I add the "database.connect" call to my setupDatabase function such as this?
var mysql = require('mysql');
var database;
//Initialise database
function setupDatabase() {
database = mysql.createConnection({
host: token.host,
user: token.user,
password: token.password,
database: token.database,
port: token.port
});
if(database != null) {
database.connect(function(err) {
if (err) throw err;
});
}
}
//Imagine this could be called at any time after execution
function event() {
if(database != null) {
database.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
}
}
My main concern is that calling the con.connect function every single time I make a query would be slow and although these are asynchronous I want to be using the correct/most efficient way possible. Feel free to correct me on any mistakes with the last two code snippets I have only tested the first one so far.
You have to make database connection only once per application livetime (unless you have disconnects). Then you may have as much queries as you want.
Just put database connection routine somewhere in sepparate file and then require it in your applicatin initialisation step.
// mysql.js
const mysql = require('mysql');
module.exports = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
Or require it anywhere you need database connection - it will return connected database object without reruning that code again and again.
// inex.js
const databse = require('./mysql')
database.query("SELECT * FROM customers")
I created a file which include a function that holds a pool and handles the connection to the database like this
let _this = {};
let POOL = null;
function getPool() {
return new Promise((resolve, reject) => {
if(POOL != null) {
resolve(POOL);
} else {
//create connection pool
POOL = connectionPool;
resolve(POOL);
}
});
}
function closePool(){
// close pool here
}
_this.getPool = getPool;
_this.closePool = closePool;
module.exports = _this;
Now you can call getPool() and will recive a pool of connections where you can execute your queries with.
I am trying to retrive data from a local SQL Express server from a node.js app, but I get an error saying:
message: 'Login failed for user \'DIR\\maja.okholm\'.',
code: 'ELOGIN' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
I have checked that the local sql server is running and that I have access.
The code in node.js:
router.get('/', function (req, res, next) {
var sql = require("mssql");
// config for your database
var config = {
user: 'DIR\\maja.okholm',
password: '******',
server: 'localhost', //CPX-Q2N4C7MBZ9L\SQLEXPRESS01 localhost (local)\SQLEXPRESS01
database: 'Retracer Pages'
};
// connect to your database
let connection = sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request(connection);
// query to the database and get the records
let result = request.query('select * from Configurations', function (err, recordset) {
if (err) console.log(err)
// send records as a response
//console.log(recordset);
res.send(recordset);
});
});
I tried to changed it to async but without luck.
Any advice is appreciated!
We are using GoDaddy. We want to connect to remote mysql by mysqljs and nodejs. It works on local server but it doesn't work on live server. We are receiving always same error:
Error: connect ETIMEDOUT
Error connecting to Db
Here is my connection code:
var con = mysql.createConnection({
domain: "http://domain.com/",
host: "domain.com",
port: 3306,
user: "username",
password: "password",
database: "databasename"
});
con.connect(function(err){
console.log(err);
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
con.query("SELECT * FROM users WHERE username='"+user+"' and password='"+pass+"' ", function(err, rows) {
if (err) throw err;
if (rows=='') {
alert('Wrong username or password');
}else {
$.each(rows , function(key,value){
if (value.username==user && value.password==pass) {
//window.location =('Home.html');
window.location =('cpanel.html');
}
});
}
});
});
I am new to node.js and am trying to learn how to connect to mysql database from ejs file. I tried to search for sample code however the code is not working. Can someone please check it out for me. Thank you.
function loaddata() {
var sql = require("mysql");
var con = mysql.createConnection({});
con.connect(function (err) {
if (err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
con.query('update students set name="sus" where email="smn14#mail.aub.edu"', function (err, rows) {
if (err) throw err;
console.log('Data received from Db:\n');
console.log(rows);
});
con.end(function (err) {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
}
The create connect is worst.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
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();
From this example, you can learn the following:
Every method you invoke on a connection is queued and executed in sequence.
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the
mysql server.
Docs
I now understand the process of server/clients. Makes sense, otherwise you would be able to see the database passwords stored in Client.js. :-)
But, there is one way that works for me. The client call a javascript-function and send a message to the server. The server receives this message and starts a database query. Send the result to all clients via socket.io
At the client in the file.ejs
<script type='text/javascript'>
let socket = io.connect();
function getSql(userId) {
socket.emit('start-new-sql-querie',{
userId: userId
});
}
socket.on('new-sql-result', function (data){ // listen for the new sql result
console.log(data.userStatus); // foo something with the new data
})
</script>
<button onclick="getSql(1)">Test sql query</button>
database connection.js at server side
const connection = {
connectionLimit: 10,
host: "localhost",
user: "Abc",
password: "1234",
database: "d001",
multipleStatements: true
};
module.exports = connection;
yourapp.js at server side
const express = require('express');
const port = process.env.PORT || 1234;
const app = express();
const server = require('http').createServer(app);
const mysql = require('mysql2');
const config = require('./routes/connection'); // SQL-Connection
const pool = mysql.createPool(config);
let io = require('socket.io')(server);
io.sockets.on('connection', function(socket) {
socket.on('start-new-sql-querie', function(data) { // listen from the clients
let user_id = data.userId;
sql_test.getConnection((error, connection) => { // Connect to sql database
console.log("user_id: ", user_id)
connection.query(`SELECT * FROM user WHERE id='${user_id}'`, (err, result) => {
socket.emit('new-sql-result',{ // send sql result-status to all clients
userStatus: result.result[0].status
})
})
connection.release();
})
});
})
I am reading this and tried to connect to MYSQL database using node js.Here is my program
var mysql = require('mysql');
var connection = mysql.createConnection({
host : "localhost",
User : "root",
password: ""
});
connection.connect();
connection.query("use test");
var strQuery = "select * from chat";
connection.query( strQuery, function(err, rows){
if(err) {
throw err;
}else{
console.log( rows );
}
})
connection.destroy( );
I an not getting any error but also unable to get any output
In order to have the program wait for your queries to be executed, replace
connection.destroy();
with
connection.end();