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.
Related
Does anyone know why my request just gets stuck loading when trying to access my database ?
My database name is test. If set the database: books or something like that for example. Then it returns the error database is unknown: books so I assume that my password is correct it just isn't finding the test data base ?
// To import these packages remember to add "type":"module" to package Json
import express from "express";
import mysql from "mysql";
const app = express();
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "keks000207",
database: "test",
});
// This is an API request with an Express server
app.get("/", (req, res) => {
res.json("Hello this is the backend");
});
app.get("/books", (req, res) => {
const q = "SELECT * FROM books";
db.query(q, (err, data) => {
if (err) return res.json(err);
return data;
});
});
app.listen(8800, () => {
console.log("Connected to backend!");
});
Try db.connect() or similar method available in the file itself.
And Instead of return data inside the callback of db.query, you should use res.send(data), then you will get the response in the GET /books API.
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!
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!
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
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();
})
});
})