How to use db.query from a .js file - javascript

Document Structure:
|-public/
|-js/
|-shop.js
|-views/
|-routes/
|app.js
I have defined my sql connection in my app.js
const mysql = require('mysql');
const db = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'password',
database: 'pfis'
});
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
global.db = db;
All sql queries under app.js work fine!
My problem is that i have a shop.js file (see directory structure) which needs to insert some sql (stored procedure) once they clicked on a button element on my page. And i can't figure out how to achieve this.
example shop.js (which is not working!):
function purchaseClicked() {
var stoel = prompt("Enter your chairnumber: ");
alert('Someone is on this way with the ATM-machine');
var cartItems = document.getElementsByClassName('cart-items')[0];
while (cartItems.hasChildNodes()) {
var itemTitle = document.getElementsByClassName('cart-item-title')[0].innerHTML;
var itemQuantity = document.getElementsByClassName('cart-quantity-input')[0].value;
db.query("Call test1_insert(" + itemTitle + ", " + itemQuantity + ", " + stoel + ");",
function (error, results, fields) {
if (error) {
alert("Something went wrong, try again!");
}
alert("Looks like all good!");
});
cartItems.removeChild(cartItems.firstChild);
}
updateCartTotal();
}
I have tried to add the same db connection code from app.js (see above snippet) in the shop.js file but it doesnt like that either.
Who can help me how to execute SQL from a "outside" .js file?

I use Sequelize for this.
Db file like this :
var sequelize = new Sequelize(mysqlDatabase, mysqlUser,mysqlPassword, {
host: mysqlHost,
dialect: 'mysql',
pool: {
max: 1000,
min: 0,
idle: 10000
},
//logging: logger.info
logging: false
});
var db = {};
db.Shop = sequelize.import(__dirname + '/models/Shop.js');
module.exports = db;
After creating db file you can reach shop like this:
const db = require('path/to/sequelize/file');
db.Shop.create(data);

Related

Canno add values to database by javascript

I am getting an error on node.js, and I cannot identify why. Can anybody help me? If I add only 1 data from the array it gets added to the database. However, when I add other inputs, it displays an error in node.js and doesn't get saved in my database.
var express = require('express');
var app = express();
app.get('/register/*', handleGetRequest); //how do I pass usrName here?
app.use(express.static('public'));
app.listen(5000);
function handleGetRequest(request, response){
var pathArray = request.url.split("/");
var pathEnd = pathArray[pathArray.length - 1];
if(pathEnd === 'register'){
response.send("{working}");
//console.log(request.body.usrName);
}
else
var registerArray = pathEnd.split("&");
response.send(JSON.stringify(registerArray));
saveToDb(registerArray);
// response.send("{error: 'Path not recognized'}");
}
function saveToDb(registerArray){
for (var i = 0; i < registerArray.length; i++) {
console.log(registerArray[i]);
}
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'customer',
port: 6000
});
con.connect();
addData();
function addData(){
var query = con.query(
"INSERT INTO cust (id,LastName,FirstName) VALUES
('001,"+registerArray[0]+"," +registerArray[1]+"');",function(err, result,
fields){
if (err) throw err;
console.log('results' , result);
}
);
}
//Close the connection
con.end();
}
You are missing single quotes in your SQL statement that cause the problem. The code should look like this:
function addData(){
var query = con.query(
"INSERT INTO cust (id,LastName,FirstName) VALUES
('001','"+registerArray[0]+"','" +registerArray[1]+"');",
function(err, result, fields) {
if (err) throw err;
console.log('results' , result);
}
);
}

ER_NO_DB_ERROR: No database though database is present

I am learning to create application using node js , I am connecting node js to mysql, the connection is successful , but after that when I am giving "select" command from node file it's throwing "ER_NO_DB_ERROR: No database selected" this error.
Below are my files :
config.js
module.export ={
server : "localhost/phpmyadmin/",
port : "3306",
database : "newdb",
username : "root",
password : ""
}
connection.js
var dbConfig = require("./config")
var sqlInst = require("mysql")
var con = {};
module.exports.createCon = function(callback){
con = sqlInst.createConnection(dbConfig);
con.connect(function(err){
if(err)
{
console.error(err);
// callback(err);
}
else{
console.log("connected");
}
})
module.exports.instSql = function(callback){
let sql = "SELECT * FROM `producdesc`";
con.query(sql,(err,result)=>{
if(err){
console.log(err);
res = err;
}
else {
res = result;
}
});
// return res;
}
}
server.js file:
const exp = require("express");
var connect = require("./connection")
const app = exp();
app.listen('3000',()=>{
console.log('server strated at port 3000');
})
app.get('/connect',(req,res)=>{
console.log("hello");
connect.createCon();
res.send("connected to database");
})
app.get('/show',(req,res)=>{
let prodRes ;
console.log("in show");
prodRes=connect.instSql();
res.send(prodRes);
})
The error comes only when I try to "http://localhost:3000/show" , the database and the table are present in the database.
Could someone please let me know the issue
In node mysql, the properties are called host and user, not server and username. https://github.com/mysqljs/mysql#connection-options
So, change your config to:
module.export = {
host: 'localhost/phpmyadmin/', // This was changed
port: 3306,
database: 'newdb',
user: 'root', // This was changed
password: ''
};

How to insert json data into mysql using node js

var express = require('express');
var app=express();
var length;
var affiliate = require('flipkart-affiliate');
var url = require('url');
var moment=require('moment');
var mysql = require('mysql');
var body;
var getUrl;
var product;
var offer;
var offer1;
var offer2;
var offer3;
var test1;
var test2;
var test3;
var title=[];
var description=[];
var startTime=[];
var endTime=[];
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'coupontest'
});
var client = affiliate.createClient({
FkAffId: 'anandhkum',
FkAffToken: 'eb030998c556443087d3b1a27ac569d0',
responseType: 'json'
});
client.getCategoryFeed({
trackingId: 'anandhkum'
}, function(err, result,getUrl){
if(!err){
body=JSON.parse(result);
getUrl=body.apiGroups.affiliate.apiListings.food_nutrition.availableVariants["v1.1.0"].get;
client.getProductsFeed({
url: getUrl
}, function(err, result){
if(!err){
}else {
console.log(err);
}
});
}
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.get('/',function (req,res) {
client.getAllOffers(null,function(err, resp){
if(!err){
offer=JSON.parse(resp);
test1=offer.allOffersList.length;
res.send(offer);
for(var i=0;i<test1;i++){
description[i]=offer.allOffersList[i].description;
startTime[i]=offer.allOffersList[i].startTime;
endTime[i]=offer.allOffersList[i].endTime;
}
var stmt = "INSERT INTO offers (description,start_time,end_time) VALUES ?";
connection.query(stmt, [description,startTime,endTime], function (err, result) {
if (err) throw err.message;
console.log("Number of records inserted: " + result.affectedRows);
});
}
else{
console.log(err);
}
});
});
app.listen(3000);
console.log("Listening to port 3000");
I'm getting the error
throw err; // Rethrow non-MySQL errors
^
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 '' 3 ports - multi device charging', 'Universal Voltage', 'Best Price Ever', 'Ext' at line 1
When doing a prepared statement, you need a ? for each of the values you bind. E.g. INSERT INTO offers (description,start_time,end_time) VALUES (?, ?, ?, ?)
It might be worthwhile to take a look at using something like the knex.js module. It uses the mysql module underneath and does the sql binding under the hood.

Global objects with Node.js + Express

I'm studying Node.js + Express, coding a basic login example. My /login route is set inside the routes/login.js file:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connectionpool = mysql.createPool({
host : 'localhost',
user : 'user',
password : 'pass',
database : 'database'
});
router.post('/', function(req,res){
connectionpool.getConnection(function(err, connection) {
if (err) {
console.error('CONNECTION error: ',err);
res.statusCode = 503;
res.send({
result: 'error',
err: err.code
});
} else {
// Do something
}
});
});
module.exports = router;
I was wondering: how can I make the mysql or the connectionpool visible in the entire application? I don't want to redeclare them on each route file I'll create. I'm looking something like an include or require method.
Any idea?
Create a separate module to act as an interface to retrieving SQL connections like so:
var mysql = require('mysql');
var connectionpool = mysql.createPool({
host : 'localhost',
user : 'user',
password : 'pass',
database : 'database'
});
exports.getConnection = function (callback) {
connectionpool.getConnection(callback);
};
Then in another file:
var connections = require('./connections');
connections.getConnection(function (err, c) {
// Use c as a connection
c.query("select * from table limit 10 ",function(err,rows){
//this is important release part
c.release();
if(!err) {
console.log(rows);
}
});
});

mySQL base authentication error in express framework

Recently I put my interest in node.js and learned a great about it and quickly move to the express framework. I've tried to connect my express application with mysql database and succeeded. Now I try to authenticate a simple login from connected with mysql database but I can't do that. Still don't get it why it is happening. Bellow here is the code I've used. A help will be greatly welcome.
var mysql = require('mysql');
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'express_db',
password: '12345'
});
connection.connect();
exports.admin_login = function (req, res) {
res.render('./admin/login', {title: 'Please provide your credentials to login'});
};
exports.admin_home = function (req, res) {
var parse = req.body;
var name = parse.name;
var password = parse.password;
var sql = "select * from user where name = " + connection.escape(name) + " and password = " + connection.escape(password);
connection.query(sql, function (err, results) {
if (err) throw err;
if (name == results[0].name && password == results[0].password) {
req.session.regenerate(function () {
req.session.name = results[0].id;
res.render('./admin/home', {username: results[0].name});
});
}
});

Categories

Resources