confusion about how connection.end() works in node.js mySQL module - javascript

const mysql = require('mysql');
let connection = mysql.createConnection(...);
connection.connect((err)=>{
...
connection.query((err)=>{
...
connection.end();});
});
After I close the connection by using
connection.end()
, if I want to query the database again using the same credentials, do I need to make a new connection by calling
mysql.createConnection(...)
Or can I reuse the same connection by simply calling
connection.connect(...)
A little background: I'm deploying an angular/node.js app to a shared hosting website, and the web host has a maximum limit of 25 concurrent connections to mySQL database, therefore I need to make sure I close a connection properly after a user does his query. I am not sure if I could reuse the connection created by mysql.createConnection(...) after I close that connection, or do I need to create a brand new connection.

You can use one global connection for getting data from db .
If You working on single file than you can write as
app.js one file only
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function (error, results, fields) {
if (error) throw error;
// connected!
});
if you want to use same connection in multiple file than you can write as
app.js
app.use(
connection(mysql, {
host: xxxxx,
user: 'root',
password : xxxx,
port : 3306,
database:dbname
},'pool'),
);
var oem = require('./routes/type');
app.get('/api/oemtype',oem.type);
For the second file
type.js
exports.type = function(req, res){
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM type',function(err,rows)
{
if(err)
res.json({
status:0
});
res.send(rows);
res.render('customers',{page_title:"Customers - Node.js",data:rows});
});
});
};
No need to use of connection.end().

Related

Connect to postgres with nodeJS

Im struggling to create API call to my database from node.js.
i have a postgres instance on Centos with multiple databases and table.
im trying to get table name "test_reslts" from database "sizing_results".
when the url, its just the server ip and port like http://{SERVER IP}:3300/
this is output -
"Cannot GET /"
when adding the table name or db name and table name, the request isn't completed and not output.
my code -
db_connection
const {Client} = require('pg')
const client = new Client({
user: 'postgres',
database: 'sizing_results',
password: 'password',
port: 5432,
host: 'localhost',
})
module.exports = client
api.js
const client = require('./db_connection.js')
const express = require('express'); // To make API calls
const app = express();
app.listen(3300, ()=>{
console.log("Server is now listening at port 3300");
})
client.connect();
app.get('/test_results', (req, res)=>{
client.query(`select * from test_results`, (err, result)=>{
if(!err){
res.send('BLABLA')
res.send(result.rows);
}
});
client.end;
})
Base on your answer to my comment I think it's not a DB connection problem.
It seems to be link to your routing, because it seems node never reach the inside of your route.
Are you sure you are calling the good route (http://localhost:3300/test_results) with no typo ? And with the good protocol (GET) ?

React: Trying to connect index.js to database but its not working

So i built a frontend where you can fill in a movie name, a review and submit it to a database. Now im trying to connect a mysql database i created to the index.js , so that it gets filled with the first entry. Im trying to accomplish it like this:
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password:"password",
database:'CRUDDatabase',
});
app.get('/', (req, res) => {
const sqlInsert = "INSERT INTO Movie_Reviews(movieName, movieReview) VALUES (1,'inception', 'good movie');"
db.query(sqlInsert, (err, result) =>{
res.send("change done");
});
})
app.listen(3001, () => {
console.log("running on port 3001")
})
But somehow the frontend gets the text ive send "Change done" but the database still doesnt show any entries. Any ideas where my mistake may be? Is it a code mistake or does it have to do with me db configuration. In mysql workbench i just created a default connection without changing anything.
EDIT: The Error seems to be the following:
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
EDIT:
The following comment here solved my problem:
Execute the following query in MYSQL Workbench ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; Where root as your user localhost as your URL and password as your password Then run this query to refresh privileges: flush privileges; Try connecting using node after you do so. If that doesn't work, try it without #'localhost' part.
I think you have an error in your code but you are not showing it as you don't test in err variable, try this code in order to show what error you are getting:
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password:"password",
database:'CRUDDatabase',
});
app.get('/', (req, res) => {
const sqlInsert = "INSERT INTO Movie_Reviews(movieName, movieReview) VALUES (1,'inception', 'good movie');"
db.query(sqlInsert, (err, result) =>{
if(err) {
console.log(err);
res.send(err.toString());
}
res.send("change done");
});
})
app.listen(3001, () => {
console.log("running on port 3001")
})
So as Med Amine Bejaoui pointed out in a comment, the solution is:
Execute the following query in MYSQL Workbench ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; Where root as your user localhost as your URL and password as your password Then run this query to refresh privileges: flush privileges; Try connecting using node after you do so. If that doesn't work, try it without #'localhost' part.

Establishing shared connection using node-mysql in node-expess app

Currently I dont use connection pooling on my settings since i only have 1-4 users in the application.
According to the doc this is the recommended way.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
Now, what i did was export the connection object and shared it to other api resources.
On db.js file
var mysql = require('mysql');
var connection = mysql.createConnection({ ... });
module.exports = connection;
On api.js file
const express = require('express');
const router = express.Router();
const conn = require('./db');
router.post('/create', function (req, res) {
connection.query('INSERT ...', function (error, results, fields) {
if (error) throw error;
// connected!
});
});
router.post('/update', function (req, res) {
connection.query('UPDATE SET ...', function (error, results, fields) {
if (error) throw error;
// connected!
});
});
AND SO ON the same goes to the other api resources that was omitted in these examples..
What is the drawback in this connection design?
Please correct me if I'm wrong. I think, even though you export the connection object, you're still managing the connection one by one.
Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources
Wikipedia
And from the same doc,
This is because two calls to pool.query() may use two different connections and run in parallel
So the best way is to use pool for managing the connections
Connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom.
Hope that helps.

ETIMEDOUT error when querying mysql database

Using sequel pro I have created a database called test. It has one table called users. In that table there is one user -> id=1, name=Phantom.
I have installed the mysql node module
When I run the code below I get The solution is: undefined.
Can anyone advise how I can connect to database and show the users?
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost:8889',
user : 'root',
password : 'root',
database : 'test'
});
connection.connect();
connection.query('SELECT * from users', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows);
});
connection.end();
It shows the following error :
Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (/Users/fitz035/Desktop/sony/presave/node_modules/mysql/lib/Connection.js:425:13)
I am running the db through MAMP. These are the db settings :
Host: localhost
Port: 8889
User: root
Password: root
Socket: /Applications/MAMP/tmp/mysql/mysql.sock
Node is asynchronous, so connection.end() is likely to happen before your query calls back. Also, specify the port Mysql is running on when non-standard.
try this :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'test',
port: 8889
});
connection.connect();
connection.query('SELECT * from users', function(err, rows, fields) {
if(err) console.log(err);
console.log('The solution is: ', rows);
connection.end();
});
If it on VPS configured with Firewall, you need to whitelist your IP via SSH. Otherwise it still throws exactly above error even after adding via cPanel's RemoteMYSQl
# csf -a [RemoteIP]
# csf -r
You can do it quickly via WHM too. Just posted as it may help someone.
Check your current MySQL server port and change to:
DB_PORT=3304

Using app.get inside the function connecting DB - NodeJs

I am using NodeJs along with MySQL. I am using node-mysql after looking at MySQL with Node.js. Now the problem is I am trying to make db connection only once and using GETs inside it but it's not working.
Code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function(err) {
// connected! (unless `err` is set)
app.get('/hello',function(req,res){
console.log('Hello');
res.send('Hi');
});
});
But the above code is not working. It is not recognizing the route. But making a connection inside every get function works.
I should be doing something wrong. Is there any way such that I can connect to the Db only once ?
You should move your call to app.get to the top level scope of the file. These calls are declarative and should be thought of more like configuring your application than the application's business logic. From the mysql docs, the connection object will automatically implicitly open a connection to the database if connection.query is called and a connection is not yet established. That sounds like the mechanism you should take advantage of.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
app.get('/hello',function(req,res){
console.log('Hello');
connection.query('select * from users', function (error, result) {
res.send('Hi');
});
});

Categories

Resources