I can't get all users, but if write manually it works.
class User {
static getAll(result) {
let sql = `SELECT * FROM users`;
sql.query(sql, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log("users: ", res);
result(null, res);
});
}
}
exports.findAll = (req, res) => {
User.getAll = (err, data) => {
if (err) return res.status(500).send({ message: err.message || "Some error occurred while retrieving users." });
res.send(data);
}
}
query() is a method of a mysql connection, you are using it as a string method:
let sql = 'SELECT * FROM users';
sql.query()
You should first create the connection with your database, and then use that connection object to make your queries, something like this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM users", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Related
let mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'priyanka',
password: '1234',
database: 'todoapp'
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
// promise function
query = `select device from user_table limit 34`;
sql = function(device){
return new Promise(function(resolve,reject)
{
connection.query(query, (error, results) => {
if (error) {
reject( console.error(error.message));
}
resolve(console.log(results));
});
})
}
sql('device').then(function(rows) {
}).catch((err) => setImmediate(() => { throw err; }));
connection.end();
sql('device') -> inside sql call , can i only place comma separated field values to get rows from user_table or is there any other way to pass multiple columns ?
Is it possible to change the pool config database?
I have a rest API with node/express, and I have multiple databases.
So I need that when a user.company login in my frontend, the API rest, choose the database that user should use.
My configuration file for the bank is this .env
JWT_KEY=XXXXXXX
POOL1_USER=root
POOL1_PASSWORD=xxxxxx
POOL1_DATABASE=data1
POOL1_HOST=host.domain.com
POOL1_PORT=3306
Meu arquivo db.js é este:
const mysql = require("mysql");
const pool1 = mysql.createPool({
connectionLimit: 10,
user: process.env.POOL1_USER,
password: process.env.POOL1_PASSWORD,
database: process.env.POOL1_DATABASE,
host: process.env.POOL1_HOST,
port: process.env.POOL1_PORT,
});
module.exports = { pool1 };
Is this my controllers.js file?
const mysql = require("../db").pool1;
exports.adminGroup = (req, res, next) => {
mysql.getConnection((error, conn) => {
if (error) {
return res.status(500).send({ error: error });
}
conn.query(
"INSERT INTO adminGroup SET ?",
[req.body],
(error, results) => {
conn.release();
if (error) {
return res.status(500).send({ error: error });
}
response = {
mensagem: "Group add",
grupoCriado: {
id: results.insertId,
grupo: req.body.group,
},
};
return res.status(201).send(response);
}
);
});
};
I need to dynamically change the database, as I have the same frontend for the same rest API, but I have multiple databases that can even be on different hosts.
It may be that what I'm trying to implement is not possible, so does anyone have any different suggestions?
Before you use the query to select a table from a database, you need to switch the database, use this query to achieve that.
con.query("USE your_db_name", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
then after it use the query that you want like this
const mysql = require("../db").pool1;
exports.adminGroup = (req, res, next) => {
mysql.getConnection((error, conn) => {
if (error) {
return res.status(500).send({ error: error });
}
con.query("USE your_db_name", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
conn.query(
"INSERT INTO adminGroup SET ?",
[req.body],
(error, results) => {
conn.release();
if (error) {
return res.status(500).send({ error: error });
}
response = {
mensagem: "Group add",
grupoCriado: {
id: results.insertId,
grupo: req.body.group,
},
};
return res.status(201).send(response);
}
);
});
};
I have tried it through MongoDB, but I can't to use JOIN Query in mongoDB and my project is wide enough. So, Want to Create Restful API in node js in MySQL.
Can anyone suggest the solution
For creating REST API you can go with express JS
var express = require('express');
var app = express();
app.get('/', function (req, res) {
//BELOW-CODE
});
You can connect Mysql by following this code:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
);
});
Note: Install expressJS framework to get started
Happy coding :-)
For MySQL with NodeJS you can use Sequelize, it's an ORM kinda like doctrine in symfony
http://docs.sequelizejs.com/
`'user strict';
var sql = require('./db.js');
//Task object constructor
var Task = function(task){
this.task = task.task;
this.status = task.status;
this.created_at = new Date();
};
Task.createTask = function createUser(newTask, result) {
sql.query("INSERT INTO tasks set ?", newTask, function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}
else{
console.log(res.insertId);
result(null, res.insertId);
}
});
};
Task.getTaskById = function createUser(taskId, result) {
sql.query("Select task from tasks where id = ? ", taskId, function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}
else{
result(null, res);
}
});
};
Task.getAllTask = function getAllTask(result) {
sql.query("Select * from tasks", function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
console.log('tasks : ', res);
result(null, res);
}
});
};
Task.updateById = function(id, task, result){
sql.query("UPDATE tasks SET task = ? WHERE id = ?", [task.task, id], function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
result(null, res);
}
});
};
Task.remove = function(id, result){
sql.query("DELETE FROM tasks WHERE id = ?", [id], function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
result(null, res);
}
});
};
module.exports= Task;
Below is a MySQL statement in my Node.js app. I used a promise in MySQL function to get API endpoint to work. Is this a typical pattern for Node.js and MySQL?
const express = require('express');
const app = express();
app.use(express.static('client'));
const config = require('./config')
var mysql = require('mysql');
var con = mysql.createConnection({
host: config.HOST,
user: config.USER,
password: config.PASSWORD,
database: config.DATABASE
});
function GetConsumers(req, res) {
return new Promise(function (resolve, reject) {
con.connect(function (err) {
if (err) throw err;
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) throw err;
//console.log(result);
resolve(result);
});
});
}).then(rows => res.send(rows));
}
app.get('/consumers', GetConsumers);
module.exports = app;
As George commented, you don't really need to return a promise here.
function GetConsumers(req, res) {
con.connect(function (err) {
if (err) {
res.send(err)
};
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) {
res.send(err)
};
//console.log(result);
res.send(result)
});
});
}
If you really want to use promises, it is always a good practice to catch the exceptions.
function GetConsumers(req, res) {
return new Promise(function (resolve, reject) {
con.connect(function (err) {
if (err){
reject(err);
}
con.query("SELECT * FROM " + config.DATABASE + ".Contracts",
function (err, result, fields) {
if (err){
reject(err);
}
//console.log(result);
resolve(result);
});
});
})
}
Call GetConsumers function where ever you want it.
GetConsumers(req,res).then(rows => res.send(rows))
}).catch(err =>{
console.log("Handle your error here");
res.send("error")
})
Mysql npm has good documentation of how to use the module. You can refer it more here
I am very new to nodejs. I am using mysql node module. This is how I use it:
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'sample'
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
var post = {PersonID: 1, Name: 'Prachi', City: 'Blore'};
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});
console.log(query.sql);
This node code works functionally. As in, it adds data to the table. But it doesn't terminate. What is the mistake which I am making?
Take a closer look at the official documentation, you have to close the connection :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
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();
Use connection.end() to close the connection
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
connection.end();
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});