I'm connecting node backend to MySQL database. When I try to add data, I'm getting a success message, but it's not getting added. Interesting part is that, initially it worked (just once), but now it's not storing the information in the database.
const mysql = require('mysql');
const express = require('express');
const bodyparser = require('body-parser');
const app = express();
app.use(bodyparser.json());
const mysqlconnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'customerdb',
multipleStatements: true
})
mysqlconnection.connect((err) => {
if (!err) console.log('DB Successfully Connected !')
else
console.log('Database Not Connected \n Error' + JSON.stringify(err));
})
app.listen(3000, (req, res) => {
console.log("Server Running on Port 3000");
})
// Insert a customer
app.post('/customers', (req, res) => {
let data = req.body;
var sql = "SET #id = ?;SET #firstname = ?;SET #lastname = ?;SET #password = ?; \
CALL CustomerAddOrUpdate(#_id,#_firstname,#_lastname,#_password);";
mysqlconnection.query(sql, [data.id, data.firstname, data.lastname, data.password], (err, rows, fields) => {
if (!err)
res.send(rows)
else
res.send(err);
})
})
It sounds interesting.
If it worked once and the API always succeed, maybe CustomerAddOrUpdate mysql function was not written correctly.
I would do this:
var sql = "INSERT INTO table (field1, field2, ...) VALUES (value1, value2, ...)";
Can't tell you what is the problem with your code, because it looks fine to me.
Related
Do you know why I can not manually add the value "Sasan" to mySQL server?
MarioDB is installed in PHPStorm and schema is correctly selcted.
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql");
const cors = require("cors");
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "Test123456",
database: "shoppingList-DB"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get("/test", (req, res) => {
const sqlInsert = "INSERT INTO shoppingList (itemList) VALUES ('Sasan')";
db.query(sqlInsert, (error, result) => {
console.log("error", error);
console.log("result", result)
res.send("Hello Express");
})
})
app.listen(5001, () =>{
console.log("Server is up - Port 5001");
})
The error is pretty clear Access denied for user 'root'#'localhost'. Check your credentials and user access in mysql.user table.
I'm trying to query a single line from a 28k record database as a test but it isn't going through but when I load up 'localhost:3001/api/get' it stays loading, even though my connection says success? Is it actually even connecting to the db?
my data bases schema is:
id | state_name | city
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/api/get', (req, res)=>{
const sqlGet = "SELECT city FROM state_city city = 'Chicago'";
db.query(sqlGet, (err, res)=>{
console.log("success");
});
});
app.listen(3001, ()=>{
console.log("running on port 3001");
});
First you must make server running. Remove that API route you had set before running server.
app.listen(3001, ()=>{
console.log("running on port 3001");
});
Now you must create database connection. Create new file dbconn.js
var mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
Now create new connection:
var new_connection = mysql.createPool(
db
);
new_connection.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
// export connection
module.exports = new_connection;
Include that connection in other file:
var db_connection = require('../dbconn');
db_connection.query(query, params, function (error, results, fields) {
//Do your query
});
Read about project structure to make your code easy to edit.
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!');
});
});
I want to connect to SQL Server where I have few databases. I am using mysql library for nodejs. What I want to achieve is to connect to SQL Server and query different databases based on send query like this.
SELECT * FROM db1 where id = 1
SELECT * FROM db2 where id = 2
etc
My code:
const express = require('express')
const mysql = require('mysql')
const fs = require('fs');
const app = express()
const db = mysql.createConnection({
host: '',
user: '',
password: '',
database: '' // I want to pass db name in SQL query below not here
})
db.connect()
app.get('/', (req, res) => {
//and here i want to pass db name in query not in above.
//so every query that i send will contain db
const sql = 'SELECT * FROM users'
db.query(sql, (err, result) => {
if (err) throw err;
res.json(result)
})
})
app.listen(5000, () => {
console.log('Server started')
})
You can just omit the database attribute in the createConnection object.
See Establishing connections
...
const db = mysql.createConnection({
host: '',
user: '',
password: ''
})
db.connect()
...
I want to display all the values from two tables from my database and display it as console.log. If I write a single query in var sql and display it as console.log(results) it works but not for multiple queries.
var express = require('express');
var app = express();
let mysql = require('mysql')
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'pitch_perfect_db2',
multipleStatements: true
})
app.get('/',(req, res) => {
connection.connect();
var sql = 'SELECT * FROM investors?; SELECT * FROM member_info?;'
connection.query(sql, function(err, results, fields){
if (!err) {
// res.send(JSON.stringify(results[0]));
// res.send(JSON.stringify(results[1]));
console.log('hey');
//console.log(results);
console.log(results[0]);
console.log(results[1]);
} else{
console.log('Error while performing query.');
}
});
connection.end();
})
//app.listen(port, () => console.log('Server Started pn port ${port}'));
app.listen(3002);
I was able to get it to work but I had to do 2 things:
First I renamed the tables to remove the question mark as it was always getting translated to a '1' and the table name no longer matched what was in the DB.
Second, I added an array to the connection.query(). After that it worked just fine.
More info here
var express = require('express');
var app = express();
let mysql = require('mysql')
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'pitch_perfect_db2',
multipleStatements: true
})
app.get('/',(req, res) => {
connection.connect();
var sql = 'SELECT * FROM investors; SELECT * FROM member_info;';
//var sql = 'SELECT * FROM investors;';
connection.query(sql, [1, 2], function(err, results, fields){
if (!err) {
res.send(JSON.stringify(results[0]) + JSON.stringify(results[1]));
console.log('hey');
//console.log(results);
console.log(results[0]);
console.log(results[1]);
} else{
console.log('Error while performing query.');
console.log(err);
}
});
connection.end();
})
//app.listen(port, () => console.log('Server Started pn port ${port}'));
app.listen(3002);
In node you don't use ; in your sql statements. Assuming both the investors and member_info tables have the same number of columns, you will need to use this:
var sql = 'SELECT * FROM investors UNION ALL SELECT * FROM member_info';
Alternatively, if investors and member_info are unrelated tables, you will need to journey into callback hell to get what you need:
app.get('/',(req, res) => {
connection.connect();
var sql1 = 'SELECT * FROM investors';
var sql2 = 'SELECT * FROM member_info?';
connection.query(sql1, function(err, investors){
if (err) throw err; //you should use this for error handling when in a development environment
console.log(investors); //this should print
connection.query(sql2, function(err, members) {
if (err) throw err;
console.log(members);
res.render('your view', {investors:investors, members:members});
});
});
});
If you decide on the latter approach, I would urge you to reconsider your database layout.
If either of the tables in your examples have a foreign key relation with each other, you should definitely be using some kind of JOIN statement on these tables, instead of a UNION.