ER_NO_DB_ERROR: No database though database is present - javascript

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: ''
};

Related

How to use db.query from a .js file

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);

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);
}
);
}

MySQL DB Pool with Node.js and Restify

I am currently developing a node.js backend for a mobile app with potentially many users. However it's my first time in developing node.js. I was following a tutorial on how to connect to a mysql database via mysql pools.
I am able to create a single mysql connection and do queries via my routes.
The problem arises once I establish the file structure mentioned in the tutorial:
dbConnect
-[models]
--users.js
-db.js
-server-ks
I am not getting an error message regarding the connection of the mysql database - even if I enter a wrong password.
// server.js
///////////////////////////// basic setup ///////////////////////////////////
var restify = require('restify');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var db = require('./db');
var users = require('./models/users');
///////////////////////////// initilisation of the server ///////////////////////////////////
var server = restify.createServer({
name: 'testUsers',
});
server.use(restify.bodyParser({ mapParams: true }));
///////////////////////////// Säuberung der URL //////////////////////////////////////////
server.pre(restify.pre.sanitizePath());
///////////////////////////// MySQL Instanz starten //////////////////////////////////////////
db.connect(db.MODE_PRODUCTION, function (err) {
if (err) {
console.log('Unable to connect to MySQL.')
process.exit(1)
} else {
server.listen(8080, function () {
console.log('Listening on port 8080 ...')
})
}
})
///////////////////////////// implementation of the routes ///////////////////////////////////
function send(req, res, next) {
var test = users.getAll();
res.json({ test: 'Hello ' + req.params.name });
return next();
};
My DB.js file looks the following:
var mysql = require('mysql'),
sync = require('async')
var PRODUCTION_DB = 'userDB',
TEST_DB = 'userDB'
exports.MODE_TEST = 'mode_test'
exports.MODE_PRODUCTION = 'mode_production'
var state = {
pool: null,
mode: null,
}
exports.connect = function (mode, done) {
state.pool = mysql.createPool({
connectionLimit: 50,
host: 'localhost',
user: 'user',
password: 'password',
database: 'userDB' // test
//mode === exports.MODE_PRODUCTION ? PRODUCTION_DB : TEST_DB
})
state.mode = mode
done()
}
exports.get = function () {
return state.pool
}
Could it be, that the tutorial spared out an essential part in utilizing mysql pools and node.js?
Thanks in advance for at least trying to answer that question.
Are there better methods sequelize(?) available to create performant connections to a MySQL database?
It looks like creating the pool object does not actually connect to the database. A big clue is that the createPool function is not asynchronous, which is what you would expect if it was actually connecting at that moment.
You have to make use of the returned pool object to perform a query, which IS asynchronous.
From the documentation:
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});

ReferenceError: connection is not defined in nodejs

Both .js files are in the same folder. And I'm attempting to run the app, but I recieve that connection is not defined in user.js. It's on the row where query is called on connection that it says that it's not defined.
index.js
var exports = module.exports = {};
var user = require('./user');
exports.User = user;
exports.startCon = startCon;
var mysql = require('mysql2');
function startCon() {
return mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'users'
})
}
user.js
var dal = require('./index');
function User(){
this.connection = null;
}
User.prototype.getAll = function(cb){
this.connection = dal.startCon();
connection.query('SELECT * FROM user;', function (error, data) {
if(!error){
cb(null, data);
}
else {
console.log("Error Selecting : %s ", error );
cb(error);
}
});
connection.end();
}
module.exports = User;
Try close connection inside the callback function
callback() {
connection.close()
}
And this module really weird
You need construct connection instance inside function
var mysql = require('mysql');
let doSmth = function(userId) {
let connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test'
});
return new Promise((resolve, reject) => {
connection.query({
sql: 'SELECT `address` FROM `User` WHERE `user_id` = ?'
},
[userId],
function (error, results, fields) {
console.log(error, results)
if(!error) {
var obj = JSON.parse(JSON.stringify(results));
resolve(obj)
} else {
reject(error)
}
}
);
})
}
module.exports = {
doSmth
};

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);
}
});
});

Categories

Resources