How to connect mysql with nodejs? - mysql

I just started to learn nodejs with express framework.In my app there are two pages app.js and db.js..I need to post data from form and insert to register table
In db.js
var mysql = require('./node_modules/mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'nodeapp'
});
connection.connect(function (err) {
if (err)
throw err;
});
module.exports = connection;
// In my app.js page
var express = require('./lib/express');
var app = express();
var bodyParser = require('body-parser')
var db = require('/db');
app.get('/', function (req, res) {
res.sendFile('/NodeProj/views/' + 'index.html');
});
/** bodyParser.urlencoded(options)
* Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
* and exposes the resulting object (containing the keys and values) on req.body
*/
app.use(bodyParser.urlencoded({
extended: true
}));
/**bodyParser.json(options)
* Parses the text as JSON and exposes the resulting object on req.body.
*/
app.use(bodyParser.json());
app.post('/process_form', function (req, res) {
var response = {
"firstname": req.body.fst_name,
"email": req.body.fst_email,
"password": req.body.fst_password
};
var query = connection.query('INSERT INTO register SET?',response,function(err,result){
if(err) throw err;
if(result) console.log(result);
});
res.end(JSON.stringify(response));
});
app.listen(8081);
But when I run the code I got the following error
Refference error: connection is not defined
Please help me .Thanks in advance.

As mentioned in the comments, you've called connection db.
So if you replace var db = require('/db'); with var connection = require('./db'); then your connection will be defined.

Related

React.js + Express: how to run SQL requests implying several databases?

I am currently working on the API of a React.js project. I have no trouble running SQL requests with databases on MySql servers using Express as long as the SQL request only implies a single database.
My problem: I now have to run an SQL request which implies using data from several databases and I do not know how to do it.
What I currently do in my server.js file to run SQL on a single database:
...
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
...
let sql = "";
...
// *************************
// CLIENT & DB CONFIGURATION
// *************************
const app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var server = app.listen(3001, "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)
});
app.use(cors());
const connection = mysql.createConnection({
host : 'myhost.fr',
user : 'someone',
password : 'aZefdt%',
database : 'SuiviTruc',
multipleStatements : true
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected with SuiviTruc database...')
});
// **************
// Request sample
// **************
app.get('/SelectAffaire_',(req, res) => {
let sql=`SELECT * FROM t_Affaire_;`
connection.query(sql, (error, result)=> {
if (error) throw error;
res.send(result);
})
})
Thanks for your help!

Error in delete DB record using Node.JS and MYSQL

I'm performing CRUD operations using MYSQL and NodeJS express. Their error in deleting a record from DB, I don't know why I was getting a problem as i have copied the delete query from SQL where it is working properly. Here it is 'DELETE FROM tblltest WHERE id=?'. I manually add 'id' like 'DELETE FROM tblltest WHERE id=2' then it will delete the record from DB. Please help me out to solve this issue. Here are my lines of code.
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'sampledb'
});
app.delete('/:id' , function(req , resp) {
connection.query('DELETE FROM `tblltest` WHERE `id`=?' , function(error , rows , fields){
if(!error){
console.log('Successful deleted!! \n');
resp.json(rows);
}else{
console.log('Error in deleting');
}
});
})
app.listen(1337);
You need to access the id route parameter in your delete API Node method, and then also bind this id value to the delete query:
app.delete('/:id', function(req, resp) {
var id = req.params.id;
connection.query('DELETE FROM tblltest WHERE id = ?', [id],
function(error, rows, fields) {
if (!error) {
console.log('Successful deleted!! \n');
resp.json(rows);
}
else {
console.log('Error in deleting');
}
});
})
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 : 'sampledb' //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(1337, "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 delete record from mysql database
app.delete('/employees', function (req, res) {
console.log(req.body);
connection.query('DELETE FROM `tblltest` WHERE `id`=?', [req.body.id], function (error, results, fields) {
if (error) throw error;
res.end('Record has been deleted!');
});
});

How to connect sql server to app.js file?

I have a folder called NEsql, located in a folder called sqlnames1. Inside the NEsql folder, I have the following files.
sqlcreatedb.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE names", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
sqlcreatetable.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "names"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a table named "customers":*/
var sql = "CREATE TABLE people (id INT AUTO_INCREMENT PRIMARY KEY, firstName VARCHAR(255), lastName VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
sqlinsertvalues.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "names"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO people (firstName, lastName) VALUES ?";
var peoplenames = [
['Vedant', 'Apte'],
['Vedant', 'Savalajkar'],
['Vinay', 'Apte'],
['Varda', 'Apte'],
['Mihir', 'Wadekar'],
['Mihir', 'Kulkarni'],
['Eesha', 'Hazarika'],
['Eesha', 'Gupte'],
['Raunak', 'Sahu'],
['Hritvik', 'Agarwal'],
['Mahima', 'Kale'],
['Shivani', 'Sheth'],
['Arya', 'Chheda'],
['Diya', 'Shenoy']
];
con.query(sql, [peoplenames], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
});
All of these files work, as I am able to complete all the tasks and successfully receive all the corresponding console.log statements. However, I am unsure as to how I am supposed to connect these files to the app.js file located inside the sqlnames1 folder. Anyone know how to do this?
Here is my app.js file.
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
What you're trying to do could simply just be the content of the app.js file you could require your package there and run these functions. However if going that route is what you choose it you could store them in a variable and then use a module.export like so
variable_name = [desired content to export]
module.export = variable_name
If you'd like to go about building a database through separate files than your app.js you should look at the package sequelize. This is more along the lines of you're trying to do.
https://www.npmjs.com/package/sequelize
Responding to your comment if you are trying to build a db upon running app.js. You are again better off looking at an ORM of some sort that will do it better than the mysql package. With it you can import the db to your app.js and simply use
require('path to db')
then using the db how you see fit, but again building your db in this way will be difficult to do as you would have to run
node filename.js
for every single one, so again if not sequelize i would strongly recommend looking at another ORM that will get this job done for you much faster and easier. As soon as you run your app.js it will build and then run, the mysql package is not the best tool to use for what it seems you are trying to do.

Angular 4 - display date from database

I need display data in table from MySql database, but I dont know how it do this.
I tried found something example or example application with source code, but I nothing found.
Maybe someone help me with this?
I tried with node.js express:
var mysql = require('mysql');
var https = require('https');
var con = mysql.createConnection({
host: "https://adress to database",
user: "user",
password: "password",
database: "db"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
But i get error:
Error: getaddrinfo ENOTFOUND
here is a simple way to get data from mySQL and export it as json:
var http = require('http');
var mysql = require('mysql');
var bodyParser = require("body-parser");
var express = require('express');
var app = express();
var pool = mysql.createPool({
host: 'db location',
user: 'username od db',
password: 'something',
database: 'yourdatabase',
port:3306
});
// define rute
var apiRoutes = express.Router();
var port = 9000;
apiRoutes.get('/', function (req, res) {
res.json({ message: 'API works' });
});
apiRoutes.get('/data', function (req, res, next) {
pool.getConnection(function (err, connection) {
if (err) {
console.error("error hapened: " + err);
}
var query = "SELECT * FROM imena ORDER BY id ASC";
var table = ["imena"];
query = mysql.format(query, table);
connection.query(query, function (err, rows) {
connection.release();
if (err) {
return next(err);
} else {
res.json({
success: true,
list_users: rows
});
}
});
});
});
app.use('/api', apiRoutes);
// starting
app.listen(port);
console.log('API radi # port:' + ' ' + port);
But i still suggest that you start using noSQL databases like firebase because of they are simple and faster.
In order to show data from MySQL Database, you need to provide application interface(s) to Angular environment and only then Angular can use the data. There are few techniques in which you can design interfaces, REST is the most popular though.
First you need to understand that Angular is Front-End framework and it can only send requests to backend such as Node js, PHP etc.Thus, first you need to chose your backend. Node is popular with express js module, but if you still don't have mySQL set, go for firebase real time database. If you decide node js => express => mySQL check tutorial online.

Create an object with mysql query

I can console.log the object that I want, but how can I retrieve the object outside of connection.query()?
var express = require('express');
var mysql = require("mysql");
var app = express();
var connection = mysql.createPool({
connectionLimit: 50,
host: "localhost",
user: "root",
password: "",
database: "sakila"
});
app.get('/', function(req, res){
connection.query('SELECT * FROM actor', function(err, rows) {
if(err) throw err;
var user = rows[0];
console.log(user);
});
res.send();
});
This is the result in the console:
node-databases> node .\database\db-1.js
RowDataPacket {
actor_id: 1,
first_name: 'PENELOPE',
last_name: 'GUINESS',
last_update: 2006-02-15T10:34:33.000Z }
I want to be able to take that and send it in the response to the browser.
Replace console.log with res.send thus sending response within the callback.