connect MySql database in WHM(phpmyadmin) to node.js - javascript

As a team, we are using node.js to setup the database connection with Mysql in Cpanel.
I did not make the database, but I know the host, user,password, database name, and port. However, in app.js, although I put all the code needed to connect to the database, it fails all the time.
Here is my code in app.js.
var mysql = require('mysql');
// creating a connection to the db
var con = mysql.createConnection({
host: 'localhost',
user: 'myUsername',
password: 'myPassword',
database: 'myDatabase',
port:3306
});
con.connect(function(err) {
if(err){
console.log('Error connecting to DB');
return;
}
console.log('Connection established');
});

Can you show the error?
By the way, you dont need to do a con.connect.
Even you use the var con = mysql.createConnection, con is a mysql resource.
Simple do this:
var mysql = require('mysql');
// creating a connection to the db
var con = mysql.createConnection({
host: 'localhost',
user: 'myUsername',
password: 'myPassword',
database: 'myDatabase',
port:3306
});
con.query('SELECT * FROM table', function(err, results) {
if(err){
console.log('Query error: ', err);
return;
}
console.log(results);
});

Related

Connection between node and mysql crash

I have a connection between Node and MySQL with a external database:
const connectionDB = mysql.createConnection({
host: '178.129.145.252',
port: 3306,
user: '',
password: '',
database: '*****'
})
when I execute my script to start it runs and I can view the users in a table, but later it crashes
enter image description here anyone knows how can I connect with the external database?
Thanks
Your code does not properly handle connection loss to MySQL server.
A quick solution would be to use connection pool.
var db_config = {
host: 'localhost',
user: 'username',
password: 'password',
database: 'example'
};
let pool = mysql.createPool(dbConfig);
pool.on('connection', function (conn) {
if (conn) {
logger.info('Connected');
}
});
// DO SOMETHING HERE
// pool.query('QUERY GOES HERE', (err, rows) => { /* Handle query response */});

Mysql node.js intermittent connectivity issue

In my node.js app I am using the mysql library for database connectivity.
When I start my node server I can query the database perfectly fine – no issues
When I query the database after 5 minutes the server returns the following error:
{"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false}
If I restart my node.js server I can query again with no issues…
Here is my code
const mysql = require('mysql');
let connection = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
connection.query(q, user, (err, results) => {
if (err)
return res.json(err);
return res.json(results);
});
});
I have used both mysql.createConnection and mysql.createPool…. also tried ending the connection manually with connection.end….
Both results end in the same error.
You need to get a connection from the pool and use that, not query the pool itself. When you get a connection from the pool, the pool will make sure you get a valid connection from the pool. So your code would be:
const mysql = require('mysql');
let pool = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
pool.getConnection(function(err, connection) {
if (err)
return res.json(err);
connection.query(q, user, (err, results) => {
if (err)
return res.json(err);
return res.json(results);
});
})
});
UPDATE:
You don't need to do separate pool.getConnection and connection.query, you can combine them into a pool.query which will get a connection, do the query and release the connection. So, the updated code would be:
const mysql = require('mysql');
let pool = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
pool.query(q, user, function(err, connection) {
if (err)
return res.json(err);
return res.json(results);
});
});

Node.js MySQL module - throw err; // Rethrow non-MySQL errors;

today I tried node.js mysql snippet from w3schools:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "roots", // WRONG USER
password: ""
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
I wanted to learn how to handle mysql errors, because my app require mysql. But after I started app.js file this error showed up:
Why can't I throw an error?
I wanted to learn how to handle mysql errors, because my app require
mysql.
MySQLJS Error handling
To catch the errors you throw, try with the following snippet :
con.on('error', function(err) {
console.log("[mysql error]",err);
});
change you're database conn like this
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});

Node + Mysql - Issue with connection

I do some mistake with connecting mysql in express which i couldn't figure out.
The basic connection code below works well.
var connection = mysql.createConnection({
host : 'localhost',
user:'root',
password:'',
database :'testdb'
});
connection.connect();
connection.query('SELECT * from test2table', function (err, data) {
if (err) throw err
console.log('The solution is: '+JSON.stringify(data)); -->could obtain data
});
But when it comes to use inside a get/post method , i donot get a response. Like code below:
var connection = mysql.createConnection({
host : 'localhost',
user:'root',
password:'',
database :'testdb'
});
connection.connect(function(err){
if(err) throw err;
console.log("connected");
});
app.get('/api/records',function(req,res){
connection.query('SELECT * from test2table', function (err, data) {
console.log(data);--> get blank response
});
});
Please let me know if i missed anything inbetween which affects. Thankyou.
Can you try with app.locals?
var connection = mysql.createConnection({
host : 'localhost',
user:'root',
password:'',
database :'testdb'
});
connection.connect(function(err){
if(err) throw err;
console.log("connected");
});
app.locals.connection = connection;
app.get('/api/records',function(req,res){
app.locals.connection.query('SELECT * from test2table', function (err, data) {
console.log(data);--> get blank response
});
});
See more details here: http://expressjs.com/en/api.html#app.locals

Node server Unable to connect the mysql database connect ETIMEDOUT at Connection._handleConnectTimeout

I am unable to connect the mysql database. When I trying to start node server many time it throw database connection error.
Error is :-
connect ETIMEDOUT
at Connection._handleConnectTimeout
Create a file mysql_yourname with:
const mysql = require('mysql');
const conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "pass",
database: "databaase"
});
conn.connect(function(err) {
if(err) throw "There is no connection to the mysql server..." + err.message;
console.info("Connected!");
});
exports.conn = conn;
then require that module in your code and you will be connected.
Connected!

Categories

Resources