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);
}
);
}
Related
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);
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: ''
};
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.
I have .js file with following code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'databasename'});
function select(id,tablename){
connection.connect();
connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result){
var string=JSON.stringify(result[0].property);
// alert(string); or console.log(string);
});
connection.end();
}
// function go(){select(3,"tablename");} or select(3,"tablename");
where function.go() is called from button.onClick().
And when I run it from console via "node filename.js" it works fine and shows correct data, but it doesn't work from button.onClick().
What am I doing wrong?
You should use single quote or double quote to enclose string.you have used ` instead of '
Also remove semicolon after host:'localhost'. there should be a comma instead of semicolon
your code should be like this
var connection = mysql.createConnection({host:'localhost',user:'root',password:'password',database: 'databasename'});
function select(id,tablename){
connection.connect();
connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {
var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */
});
}
your code is wrong.
You have written
var mysql = require(‘mysql'); var connection = mysql.createConnection({host: ‘localhost';user: 'root',password: 'password',database: ‘databasename'});function select(id,tablename){connection.connect();connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */});
It should be
var mysql = require('mysql'); var connection = mysql.createConnection({host: 'localhost';user: 'root',password: 'password',database: 'databasename'});function select(id,tablename){connection.connect();connection.query('select ' +tablename+'.property from databasename.'+tablename+' where id = '+id, function(err,result) {var string=JSON.stringify(result[0].property);/* alert(string); or console.log(string); */});
At many places, you have started strings with ‘ and ended with ' which might be causing the problem.
i think you mix sync and async. you need your callback for the query
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'databasename'
});
function select(id, tablename, callback){
connection.connect();
connection.query(`SELECT ${tablename}.property from databasename.${tablename} where id = ?`, [id], callback);
connection.end();
}
function go () {
select(3, "tablename", function (err, result) {
// mysql response
});
}
I am still new to nodejs and Javascript, I am sorry if my question appear to be very simple but I am struggling a lot and I can't seem to find an answer on the net.
What I want to do is basically calling a script (sqlRequest.js) and send an integer while calling it. This script will send an sql request to my database and will return the result (an object) to the original file.
Here are the codes:
router.post('/request', function(req, res, next){
var id = req.body.id;
var essai = require('./sqlRequest.js');
console.log("INDEX: "+essai.sendSQL(id)); });
And now the sqlRequest.js code:
exports.sendSQL = function(id) {
var mysql= require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'bcombes',
password : 'bertrand1994',
database : 'totalkpi'
});
connection.connect();
var sql ="SELECT * FROM tra_ticket where id=?";
var insert=[id];
sql=mysql.format(sql, insert);
connection.query(sql, function(err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
return rows;
}
});};
On the console I can see that the console.log("INDEX: "+essai.sendSQL(id)); appears to be undefined and is displayed before the console.log(rows).
Is it possible that the server does not wait for the function to finish and display the variable anyway ?
Anyway thank you for taking the time to help.
Your logic to pass a variable between files is fine. The reason your seeing essai.sendSQL(id) return undefined is because connection.query(...) is called asynchronously and, as you've mentioned in your question, the console.log fires before the DB query completes.
To fix that issue you just need to refactor your code slightly:
var essai = require('./sqlRequest.js');
router.post('/request', function(req, res, next){
var id = req.body.id;
// send callback to sendSQL
essai.sendSQL(id, function(index) {
// this will only fire once the callback has been called
console.log("INDEX: " + index)
})
});
And then in sqlRequest.js:
exports.sendSQL = function (id, cb) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'bcombes',
password: 'bertrand1994',
database: 'totalkpi'
});
connection.connect();
var sql = "SELECT * FROM tra_ticket where id=?";
var insert = [id];
sql = mysql.format(sql, insert);
connection.query(sql, function (err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
// call the callback
cb(rows);
}
});
};