ReferenceError: connection is not defined in nodejs - javascript

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

Related

Establishing database connection between node.js angular and mysql workbench

Im learning from a ready application and im trying to make the connection so the app to start working and save data.
picture of the hostname and port
I done the connectin also make a 'employees database' with the two tables that I need
picture of the schema
The server is running on localhost 3000 and the front end is listening on port 4200. This is the code for the connection and creating the database/schema.
config.json
{
"host": "localhost",
"user": "cveto",
"database": "employees",
"password": "1234567"
}
database.js creating pool
const mysql = require('mysql2');
const config = require('../config/config.json');
const pool = mysql.createPool({
host: config.host,
user: config.user,
database: config.database,
password: config.password,
});
module.exports = pool.promise();
And some query models
const db = require('../util/database');
module.exports = class Employee {
constructor(names, address, number, salary) {
this.names = names;
this.address = address;
this.number = number;
this.salary = salary;
}
static fetchAll() {
return db.execute('SELECT * FROM employees');
}
static save(employee) {
return db.execute(
'INSERT INTO employees (names, address, number, salary) VALUES (?, ?, ?, ?)',
[employee.names, employee.address, employee.number, employee.salary]
);
}
static delete(id) {
return db.execute('DELETE FROM employees WHERE id = ?', [id]);
}
};
I just want to know how I can make the connection so the app to work and save to my database the users and new employees. The code is from public repositority so the code is working, its now from the code its from tha database or server conncetion.
DB.js File
var mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit: 100,
host : 'localhost',
user : 'root',
password : '',
database : '',
});
let myDb = {};
myDb.searchDataQ = (query) => {
return new Promise((resolve, reject) => {
pool.query(query, function (err, rows) {
if (err) {
reject(err);
}
resolve(rows)
})
});
};
module.exports = myDb;
Other JS File to execute
const db = require('../db/db');
function testMethod() {
let query = 'SELECT * FROM employees';
return new Promise(async (resolve, reject) => {
try {
resolve(await db.searchDataQ(query));
} catch (e) {
reject(0);
}
});
}

How to correctly write module in Node.JS?

So I'm trying to make it so I don't have to have multiple connections to my database when I can just put my connection and runQuery function in a file and just require it in another file. Here is what I have in my "mysql.js" file.
const mysql = require('mysql');
module.exports = function () {
let connection = mysql.createConnection({
host: '------',
user: 'voltclou_site',
password: '----',
database: process.env.database
})
connection.connect(function(err) {
if (err) {
console.error('[DATABASE] Error connecting: ' + err.stack);
return;
}
console.log('[DATABASE] Connected as id ' + connection.threadId);
});
async function runQuery(query, values) {
return new Promise((resolve, reject) => {
connection.query(query, values, function (error, results) {
if (error) return reject(error)
return resolve(results)
})
})
}
}
Here is how I would like to require it in my files:
const { connection, runQuery } = require('./functions/mysql')
Am I doing this correctly? I'm new to this whole module thing. I've been trying to split my files up because one index.js with 3000+ lines is insane. Thanks for any help.
No you didnt do it correclty. What you have done you have exported it as an default but you want to export named functions. You can do it like:
const mysql = require("mysql");
let connection = mysql.createConnection({
host: "81.19.215.6",
user: "voltclou_site",
password: "yogO{6,F#8WS",
database: process.env.database
});
connection.connect(function(err) {
if (err) {
console.error("[DATABASE] Error connecting: " + err.stack);
return;
}
console.log("[DATABASE] Connected as id " + connection.threadId);
});
async function runQuery(query, values) {
return new Promise((resolve, reject) => {
connection.query(query, values, function(error, results) {
if (error) return reject(error);
return resolve(results);
});
});
}
module.exports = {
connection,
runQuery
};
The value you've described, { connection, runQuery }, should be the value assigned to module.exports:
const mysql = require('mysql');
let connection = mysql.createConnection({ ... });
connection.connect(...);
let runQuery = async (query, values) => { ... };
module.exports = { connection, runQuery };
You may not even need to export connection, if all you need elsewhere is runQuery!

Node MYSQL exports returns undefined

I am creating a discord bot that has integration with mysql. To make it easier, I created a central file for the mysql database (configs/mysql.js) and, when the command needs it, it will send the query request to that file and finally, it will return the processed value. But when I try to do this, the return is undefined in the console (of the command), but in the mysql.js console, it shows the correct value.
MYSQL.js Code
const mysql = require("mysql");
const connection = mysql.createConnection({
host: config.URL,
user: config.dbUser,
password: config.dbPassword,
database: config.database
});
connection.connect(function(err) {
if (err) {
console.error("[MYSQL] Error on Connection: " + err.stack);
return;
}
console.log("[MYSQL] Connected with ID " + connection.threadId + "!");
});
function query(sql) {
connection.query(sql, function(error, result, fields) {
if (error) return error;
const analise = JSON.stringify(result[0]);
console.log(analise) //it's return the value correct
return analise
});
}
exports.connection = connection;
exports.query = query;
The Request
const status1 = await mysql.query("SELECT `status` FROM `server_status`");
console.log(status1); //it's return undefined
Can anyone help me?
Use promise for mysql you can`t use return in callback function.
const mysql = require('mysql');
const connection = mysql.createConnection({
host: config.URL,
user: config.dbUser,
password: config.dbPassword,
database: config.database,
});
connection.connect(function(err) {
if (err) {
console.error('[MYSQL] Error on Connection: ' + err.stack);
return;
}
console.log('[MYSQL] Connected with ID ' + connection.threadId + '!');
});
function query(sql) {
return new Promise(resolve => {
connection.query(sql, function(error, result, fields) {
if (error) return error;
const analise = JSON.stringify(result[0]);
console.log(analise); //it's return the value correct
resolve(analise);
});
});
}
exports.connection = connection;
exports.query = query;
const status1 = await mysql.query("SELECT `status` FROM `server_status`");

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

node.js get results of mysql outside of the function

I want to get "information" in this case but have to be necessarily outside of the funtion
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'db_name'
});
connection.connect();
var insert = {
information : something
};
var query = connection.query('insert into db.table set ?', insert, function (err, result) {
if (err) {
console.error(err);
return;
}
else {
**getInformation = results;**
}
console.error(result);
});
connection.end();
I'm trying but doesn't work
console.log(getInformation)
You are calling conneciton.end() before the callback gets invoked.
Try the following:
connection.connect();
var insert = { information : 'something' };
var query = connection.query('insert into db.table set ?', insert, function (err, result) {
if (err) {
console.error(err);
return;
}
console.log(result);
connection.end();
});

Categories

Resources