Connection Error when Connection to SQL Server from Node.js - javascript

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!

Related

How to create a loop for SELECT function, to keep data updated?

I'm using an Oracle database, and every time it updates, the server doesn't understand this update and needs me to drop it for it to update the data.
const express = require('express');
const oracledb = require('oracledb');
const app = express();
var cors = require('cors')
app.use (cors())
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// Connection details for the Oracle database
const connectionString = 'dbprod';
const user = 'sapiensproducao';
const password = 'fabrica';
// Connect to the database
oracledb.getConnection(
{
connectionString: connectionString,
user: user,
password: password
},
function(err, connection) {
if (err) {
console.error(err.message);
return;
}
console.log('Connection was successful!');
// Execute a SQL query
const query = 'SELECT CODEMP,CODORI,NUMORP,SEQEOQ,DATREA,HORREA,CODPRO,CODDER,QTDRE1,QTDRFG,CODLOT,OBSEOQ from USU_VPROEXT ORDER BY DATREA DESC, HORREA DESC';
connection.execute(query, [], (err, result) => {
if (err) {
console.error(err.message);
return;
}
console.log('Query was successful!');
console.log()
// Render the HTML template and pass the query results as a local variable
app.get('/teste', (req, res) => {
res.json(result.rows)
});
});
}
);
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
I thought of creating a loop for this SELECT function, but how can I create it?
How can I keep running this select in a loop, to keep the data always updated?
In the structure of your web server, you only ever query the database once and then create an endpoint to serve that data. Instead, create an endpoint which queries the data whenever it's invoked. Which may look more like this:
// define the endpoint
app.get('/teste', (req, res) => {
// within the endpoint, query the database
oracledb.getConnection(
{
connectionString: connectionString,
user: user,
password: password
},
function(err, connection) {
if (err) {
console.error(err.message);
// DON'T DO THIS, return an actual response to the user
return;
}
console.log('Connection was successful!');
const query = 'SELECT CODEMP,CODORI,NUMORP,SEQEOQ,DATREA,HORREA,CODPRO,CODDER,QTDRE1,QTDRFG,CODLOT,OBSEOQ from USU_VPROEXT ORDER BY DATREA DESC, HORREA DESC';
connection.execute(query, [], (err, result) => {
if (err) {
console.error(err.message);
// DON'T DO THIS, return an actual response to the user
return;
}
console.log('Query was successful!');
console.log();
// return the results to the user
res.json(result.rows);
});
});
});
The key difference here is that instead of wrapping the endpoint in the query, you wrap the query in the endpoint. So every time the endpoint is invoked it re-queries the database.
Please also note the comments for your error handling. If you just return; from the function and never return a response to the client, the client will just hang until it times out. Return an actual response, which can include error codes, messages, anything you like. Even just res.json(false); would be better than no response at all.

Unable to post to my database mySQLWorkBench using express.js node.js

I am struggling to wrap my head around all this backend stuff. I basically have set up an amazon mySQL server with RDS and using mySQLWorkBench I have connected my express.js with the following file:
let mysql = require('mysql');
var connection = mysql.createConnection({
host: "",
user: "admin",
password: "",
});
connection.connect(function(err) {
if (err) throw err;
connection.query('CREATE DATABASE IF NOT EXISTS main;');
connection.query('USE main;');
connection.query('CREATE TABLE IF NOT EXISTS cars(id int NOT NULL AUTO_INCREMENT, manufacturer varchar(100), model varchar(100), price int, PRIMARY KEY(id));', function(error, result, fields) {
console.log(result);
});
connection.end();
});
module.exports = connection;
I already have my table set up in mySQLWorkbench, and and the connection is fine if I user the following in my server file:
connection.connect(function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
console.log('Connected to database.');
});
connection.end();
However in my Index.js, I am trying to create a post endpoint (im still very new to this and not sure where I should start etc, but I was following this tutorial: https://stackabuse.com/using-aws-rds-with-node-js-and-express-js/ ).
index.js:
const express = require('express');
const app = express();
const port = 3000;
const connection = require("./server");
app.listen(port, () => console.log("listening on port 3000") + port )
const dummyData = [
{manufacturer: "volvo", model: "1st", price: 300},
{manufacturer: "fiat", model: "500", price: 500},
];
app.post('/cars', (req, res) => {
if (req.query.manufacturer && req.query.model && req.query.price) {
console.log('Request received');
connection.connect(function(err) {
connection.query(`INSERT INTO main.cars (manufacturer, model, price) VALUES ('${req.query.manufacturer}', '${req.query.model}', '${req.query.price}')`, function(err, result, fields) {
if (err) res.send(err);
if (result) res.send({manufacturer: req.query.manufacturer, model: req.query.model, price: req.query.price});
if (fields) console.log(fields);
console.log(result)
});
});
} else {
console.log('Missing a parameter');
}
});
I am really not sure if I am doing this correctly, but when I run the file and host it, it's fine, then when I try use postman to do a post request with the following fields:
localhost:3000/cars?manufacturer=test&model=testmodel&price=2000
I get the following error:
{
"code": "PROTOCOL_ENQUEUE_AFTER_QUIT",
"fatal": false
}
My goal is here, is to have a few simple endpoints for my datastore, which is to post, retrieve and update. Any help for clarification or guides would be extremely appreicated. Thanks!

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.

nodeJS - how i connect with MySQL and display the result in localhost

I wrote this code
var http = require('http');
var express = require('express');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'nodejs'
});
connection.connect(function (err) {
if (!err) {
connection.query('SELECT * FROM nodetest', function (err, rows) {
if (err) {
console.log(err);
return;
}
var json = JSON.parse(JSON.stringify(rows))[0];
console.log(json);
});
console.log("Database is connected");
} else {
console.log("Error connecting database");
}
});
http.createServer(function (request, response) {
response.writeHead(200, {
"Content-Type": "test/html"
});
response.end('here my data');
}).listen(7777);
and I have a problem with display the result in my localhost as i json
what is the bast way to read table and convert it to json and display in localhost
what does JSON.stringify do?
The JSON.stringify() method converts a JavaScript value to a JSON
string, optionally replacing values if a replacer function is
specified, or optionally including only the specified properties if a
replacer array is specified.
What does JSON.parse do?
The JSON.parse() method parses a JSON string, constructing the
JavaScript value or object described by the string.
So basically, one operation is the inverse of the other. And therein lies your problem:
var json = JSON.parse(JSON.stringify(rows))[0];
Since you are requiring express, I'm assuming you want to use it.
You can create an index route with app.get('/', function(req,res){}). A fast way to display your data as json from your mysql database would be:
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'nodejs'
});
// localhost:7777/
app.get('/', function(req, res) {
connection.connect(function(err) {
if (!err) {
connection.query('SELECT * FROM nodetest', function(err, rows) {
if (err) {
console.log(err);
return;
}
var json = JSON.parse(JSON.stringify(rows))[0];
res.send(json); // Send the JSON back as a application/json type response.
});
console.log("Database is connected");
} else {
console.log("Error connecting database");
}
});
})
app.listen(7777, function() {
console.log('Example app listening on port 7777!')
});

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