PROTOCOL_CONNECTION_LOST Nodejs SQL - javascript

I already checked all answers I could found, but they don't work for me.
I get suddenly this below error, so My NodeJs can't connect to the SQL Database.
PROTOCOL_CONNECTION_LOST
I need your help.
here is the simple Code:
var path = require('path');
var mysql = require('mysql');
var express = require('express');
var fs = require('fs');
app = express();
//Connection to nagios
var connection1 = mysql.createConnection({
host : 'md1dk69c.propa.net',
user : 'userName',
password : 'pswd',
database : 'dbName',
port: 5468,
timezone: 'Europe/Berlin'
});
connection1.connect(function(err){
if(!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting to database ... nn");
console.log("code: ",err.code);
console.log("fatal: ",err.fatal);
console.log("sql: ",err.sql);
console.log("sqlMessage: ",err.sqlMessage);
}
});
app.use(express.static('view'));
app.get("/",function(req,res){
res.sendFile(path.join(__dirname + '/view/proj.html'));
});
app.get("/page",function(req,res){
var sql1 ='SELECT xxx...';
connection1.query(sql1 , function(err, rows, fields) {
if (!err)
{ res.end(JSON.stringify(rows));
console.log('I am still connected to Database..');
}
else
{
console.log('Error while performing the Query.');
connection1.end();
}
});
});
app.listen(3000);
I get as Output :
Error connecting to database ... nn
code: PROTOCOL_CONNECTION_LOST
fatal: true
sql: undefined
sqlMessage: undefined

Related

How to set two root endpoints in one file Restful API with node.js & EXPRESS

I have root endpoint who work when users enter the url like this:
http://localhost:8000/?date=2019-10-20&station=41027&daysForward=3
I want to create second root endpoint in the same file with different query but that did not work.
My code:
// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')
app.use(cors())
// Server port
var HTTP_PORT = 8000
// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%",HTTP_PORT))
});
var con = mysql.createConnection({
host: "192.168.1.1",
port: "3456",
user: "user",
password: "pass"
});
var con2 = mysql.createConnection({
host: "192.168.1.1",
port: "3456",
user: "user",
password: "pass"
});
let aladinModel= '';
let aladinModelStations = '';
app.route('/')
.get(function(req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
const date = req.query.date;
const station = req.query.station;
const daysForward = req.query.daysForward;
try {
const query = `CALL aladin_surfex.Get_mod_cell_values_meteogram('${date}', ${station}, ${daysForward})`;
con.query(query, function (err, result, fields) {
if (err) throw err;
aladinModel = result;
});
res.json({aladinModel})
} catch(error){
console.log("Error query database!!!");
}
});
app.route('/stations')
.get(function(req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
try {
const query2 = `SELECT Station,Ime FROM stations_cells`;
con2.query2(query2, function (err, result2, fields) {
if (err) throw err;
aladinModelStations = result2;
});
res.json({aladinModelStations})
} catch(error){
console.log("Error query database!!!");
}
});
app.use(function(req, res){
res.status(404);
});
I guess this is not the right way to route pages but I hope someone can explain to me with an example how I could fix the code - so when a user enters:
http://localhost:3000/stations
the data should be loaded.
I see this error when I try to open this link.
[nodemon] starting `node server.js localhost:8000`
Server running on port 8000
Error query database!!!
This query
SELECT station, ime
FROM stations_cells
on the second root point is fine. I try to SELECT with HeidiSQL and database return the data values ?
Where is the problem for the second root point ?
That might not be the case, but here's the suggestion (which doesn't fit in comment section)
app.route('/')
.get(function(req, res) {
// omitted
});
app.route('/stations')
.get(function(req, res) {
// omitted
});

How connect MySQL to Node.js CRUD

I've been using mongoDB forever. How do I switch over to MySQL? Currently, I have no idea where to look. Should I use MySQL workbench? PGAdmin4? How the heck do I go about doing this or learning to do this?
Try the JavaScript mysql package. It's the most popular package for working with MySQL in JavaScript, and the GitHub readme should walk you through most steps on using it.
If you'd like a second option, I've also had experience with the node-mysql package (which depends on the mysql package). It's a bit simpler to use and it worked great for me as well.
I added in this post, How to work with MySQL in Nodejs.
Step 1: Create table in you MySQL DB:
CREATE TABLE IF NOT EXISTS `employee` (
`id` int(11) NOT NULL COMMENT 'primary key',
`employee_name` varchar(255) NOT NULL COMMENT 'employee name',
`employee_salary` double NOT NULL COMMENT 'employee salary',
`employee_age` int(11) NOT NULL COMMENT 'employee age'
);
Step 2: Install all package using this command :
npm install --save mysql express body-parser
Step 3: Create app.js File in same directory
var http = require("http");
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
//start mysql connection
var connection = mysql.createConnection({
host : 'localhost', //mysql database host name
user : 'root', //mysql database user name
password : '', //mysql database password
database : 'dummy_db' //mysql database name
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})
//end mysql connection
//start body-parser configuration
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
//end body-parser configuration
//create app server
var server = app.listen(3000, "127.0.0.1", function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
//rest api to get all results
app.get('/employees', function (req, res) {
connection.query('select * from employee', function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
//rest api to get a single employee data
app.get('/employees/:id', function (req, res) {
console.log(req);
connection.query('select * from employee where id=?', [req.params.id], function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
//rest api to create a new record into mysql database
app.post('/employees', function (req, res) {
var postData = req.body;
connection.query('INSERT INTO employee SET ?', postData, function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
//rest api to update record into mysql database
app.put('/employees', function (req, res) {
connection.query('UPDATE `employee` SET `employee_name`=?,`employee_salary`=?,`employee_age`=? where `id`=?', [req.body.employee_name,req.body.employee_salary, req.body.employee_age, req.body.id], function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
//rest api to delete record from mysql database
app.delete('/employees', function (req, res) {
console.log(req.body);
connection.query('DELETE FROM `employee` WHERE `id`=?', [req.body.id], function (error, results, fields) {
if (error) throw error;
res.end('Record has been deleted!');
});
});
Step 4: Start the server using this command:
node app.js
Follow this link if you face any issue.

MongoError: topology was destroyed(when finding the documents) and instance pool was destroyed (when inserting documents)

I'm trying to build REST API with Node.js, Express and Mongodb. I'm using mongodb npm package to connect to the database, below is my sever.js file code
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.PORT || 8080;
var mongo = require("mongodb");
var Server = mongo.Server;
var Db = mongo.Db;
var ObjectID = mongo.ObjectID;
try{
var config = require('./configure.js');
}catch(e){
console.log("configuration file is hidden on github for security");
config = null;
}
var usersCollection = config.usersCollection;
var login = require('./routes/login/index.js');
var signup = require('./routes/signup/index.js');
var Database = new Db(process.env.DBNAME || config.DBNAME , new Server(process.env.DBHOST || config.DBHOST, process.env.DBPORT || config.DBPORT, {'native_parser': true}));
Database.open(function (err, mongoclient) {
if(err){
console.log("Failed to connect to the database. Please Check the connection");
throw err;
}else{
Database.authenticate(process.env.DBUSER || config.DBUSER, process.env.DBPASS || config.DBPASS, function(err, res) {
if (err) {
console.log("Authentication Failed");
throw err;
}else{
console.log("Connected to the database Successfully");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var users = Database.collection(usersCollection);
login(app,users);
signup(app,users);
Database.close();
}
});
}
});
app.listen(port,function(){
console.log("Server Started Listening to port : "+port);
});
routes/login/index.js
module.exports = function(app,users){
app.route('/login')
.post(function(req,res){
var username = req.body.username;
var password = req.body.password;
var query = {'FirstName':username};
users.find().toArray(function(err,docs){
if(err){
throw err;
}else{
console.log("no err");
if(doc.LastName == password){
res.send({status : true});
}else{
res.send({status : false});
}
}
});
});
}
and routes/signup/index.js
module.exports = function(app,users){
app.route('/signup')
.post(function(req,res){
var doc = { EmpNo:"1",
FirstName:"Andrew",
LastName:"Neil",
Age:"30",
Gender:"Male",
Skill:"MongoDB",
Phone:"408-1234567",
Email:"Andrew.Neil#gmail.com",
Salary:"80000"
};
users.insert(doc,function(err,info){
if(err){
throw err;
}else{
console.log('Successfully inserted ' + JSON.stringify(info));
res.send({result: 'done'});
}
});
});
}
When i'm trying to insert documents in server.js , i'm able to insert them successfully but through routes/signup/index.js i'm getting instance pool was destroyed similarly if i try to find the documents in server.js no error but if i try to do it from routes/login/index.js then i'm getting error as topology was destroyed.
Need help to resolve it.
Those errors are thrown if connection is somehow cut in the middle of the process.
Because both users.find() and users.insert() functions are async your server.js file reaches to the Database.close() function and closes the connection to your database before it finishes the process thus giving the errors.

getting Error: ER_PARSE_ERROR while inserting a dynamic values using node js and mysql

I am trying to insert the dynamic field values to mysql database using node js. In my server console am getting this error:
{ [Error: ER_PARSE_ERROR: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near
'[object Object]'f2a06305-7e98-4462-9ba2-72ce85fa4d32','undefined',
'59a3ff90-aa4a' at line 1]
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
index: 0
}
What does the error mean and how do I resolve it? Below is the server code:
var mysql=require('mysql');
var http=require('http');
var uuid = require('node-uuid');
var path=require('path');
var express=require('express');
var app=express();
var bodyparser=require('body-parser');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: true}));
var myconnection = mysql.createConnection({
host : "localhost",
user : "root",
password : "",
database : "siva"
});
app.use(express.static(__dirname + ""));
var uqid= uuid.v1();
var it_id=uuid.v4();
var tt=1;
var status="active";
app.post("/insert",function(req,res){
console.log(req.body);
/* TODO: Now just check that your drive function is correct, SQL is correct and whether what arguements passed to SQL callback is correct */
myconnection.query('Insert into cate_tbl (`cat_id`,`cat_name`,`cat_desc`,`cat_view_count`,`cat_status`) VALUES ("'+uqid+'","'+req.body.cat_name+'","'+req.body.cat_desc+'","'+tt+'","'+status+'")',function(err, results, fields) {
//if (err) throw err;
if (err){
console.log("DB Error"+err);
res.send("add cate_tbl failed"+err);
}else {
generateQuery = function(data,tableName){
var fields = Object.keys(data);
var values = [];
for(var o in data) {
values.push(data[o]);
}
return "Insert into "+tableName+"("+fields.join("cat_it_id,cat_it_name,cat_pid,cat_it_count,cat_it_desc,cat_it_status")+") values ("+values.join("'"+it_id+"','"+req.body.item_name+"','"+uqid+"','"+req.body.tem_count+"','"+req.body.item_desc+"','"+status+"'")+")"
}
var query = generateQuery(req.body,"cate_item");
myconnection.query(query,function(err, results, fields) {
//your logic.
if(err)
{
console.log(err);
}
else
{
res.end(JSON.stringify(fields));
}
});
}
});
});
app.get('/',function(req,res){
res.sendfile("index.html");
});
app.listen(3000,function(){
console.log("It's Started on PORT 3000");
})

connecting to mysql from ejs file

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();
})
});
})

Categories