I have a nodejs code like this
const mysql = require('mysql');
const express = require('express');
const app = express();
class ConnectDatabase{
constructor(){
this.connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydatabase'
});
};
getVersion() {
this.connection.query('SELECT * FROM version', function (err, results) {
return results[0].version // if use console.log() i get my data
});
};
};
var APP = new ConnectDatabase()
console.log(APP.getVersion());
when i use console.log(results[0].version), i get my data, but when i use return my data becomes undefined
I am Node js Developer i am using mongodb. i think everything fine.
3 possible problem
1 first check xampp is running
2 connection build with database or not
3 table name
Related
I try to connect to postgreSQL database and display the results in my html file.
I use node-postgres module version ^7.7.1
My code is:
const express = require('express');
const { Pool, Client } = require('pg');
const pg = require('pg');
const config = {
user: 'username',
database: 'db_name',
password: 'userpass',
port: 3000
};
app.get('/', function (req, res) {
const pool = new pg.Pool(config)
const client = new pg.Client(connect);
// connection using created pool
pool.connect(function(err, client, done) {
client.query('SELECT * FROM example_table')
res.render('index')
done()
})
pool.end()
});
I'm getting error: Cannot read property 'query' of undefined.
What's the proper way to connect to database and render the result ?
I am creating a application that will communicate over Udp protocol in node js. Also i am using sql server as a database so in order to connect this database i am using mssql npm liabrary. Basically what i am doing i have one separate module for dbcon as shown below
const sql = require('mssql')
const config = {
user: 'sa',
password: '123',
server: '192.168.1.164', // You can use 'localhost\\instance' to connect to named instance
database: 'SBM-EMCURE',
options: {
encrypt: false // Use this if you're on Windows Azure
}
}
sql.connect(config, err => {
})
sql.on('error', err => {
console.log('error on sql.on()');
})
module.exports.sql = sql;
And i am using this exported sql object to run my queries outside dbcon module but it gives me different behavior sometimes like query executes before databse connection, is there is any way to use single database connection for entire application?. Using single database connection is useful or it will slow down my process
Thanks in advance
You could:
Pass the instance into each router and use it there when you set them up
Set the instance as a property of your app object and access it from req.app.sql or res.app.sql within your middleware functions
Set the instance as a property of the global object and access it from anywhere (typically not a best practice though)
Also, in your example code, you're initiating the connection by calling sql.connect(), but you don't give it a callback for when it's finished connecting. This is causing it to be immediately exported and probably queried before the connection is actually established. Do this:
const util = require('util');
const sql = require('mssql');
const config = {
user: 'sa',
password: '123',
server: '192.168.1.164',
database: 'SBM-EMCURE',
options: {
encrypt: false
}
};
module.exports = util.promisify(sql.connect)(config);
Then you can retrieve the instance with:
const sql = await require('./database.js');
first you should create file database.js:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'event'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
Then you can use this connection in server.js or any other file.
var express = require('express');
var app = express();
var dbcon = require('./database');
app.get('/getEvent',function(req,res){
dbcon.query('SELECT * FROM eventinfo',function(err, result) {
if (err) throw err;
});
});
app.listen(3000);
I'm learning Node js and I'd like to understand why the output or result set is showing twice in the browser (tried with different browsers) and how to fix the issue to show the result set only once.
Here is my sample code :
// JavaScript source code
var express = require('express'); // Web Framework
var app = express();
var sql = require('mssql'); // MS Sql Server client
// Connection string parameters.
const pool = new sql.ConnectionPool({
user: 'myuser',
password: 'password123',
server: 'localhost',
database: 'Sample'
})
var conn = pool;
// Start server and listen on http://localhost:8080/
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log("app listening at http://%s:%s", host, port)
});
app.get('/groups', function (req, res) {
conn.connect().then (function() {
var request = new sql.Request(conn);
request.query('SELECT TOP 10 * FROM [Sample].[Table1]',function(err, recordset) {
if(err) console.log(err);
res.end(JSON.stringify(recordset)); // Result in JSON format
conn.close();
});
});
})
please advice.
Thanks.
What does createConnection do?
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
I'm writing an application in nodeJS using mysql module. I have some own modules, for example authentication, which definetely needs DB connection. Question is: if I have multiple modules where I use this method to create the connection, will it create a new connection for me everytime or use the first one? If creates, it creates the first time it loads my own module or everytime? Oh, and if it creates when is it going to be destroyed?
Here's how I have it in my authentication module:
var config = require('./config.js');
var mysql = require('mysql');
var connection = mysql.createConnection(config.connectionString);
exports.login = function() ...
I have some basic understanding missings about how modules and own modules work.
Thanks for the answers.
You can create a connection pool in one module and then share that pool across all your modules, calling pool.getConnection() whenever you need to. That might be better than keeping a single, shared connection open all the time.
One project I'm working on does this:
utils/database.js
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'xxxxx',
password: 'yyyyy',
database: 'zzzzz',
debug: false
});
module.exports = pool
accounts.js
var express = require('express');
var router = express.Router();
var pool = require('./utils/database');
router.get('/', function(req, res) {
pool.getConnection(function(err, connection) {
// do whatever you want with your connection here
connection.release();
});
});
module.exports = router;
Another way I'm playing around with is like this:
utils/database.js
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'xxxxx',
password: 'yyyyy',
database: 'zzzzz',
debug: false
});
var getConnection = function(callback) {
pool.getConnection(function(err, connection) {
callback(err, connection);
});
});
module.exports = getConnection;
accounts.js
var express = require('express');
var router = express.Router();
var createConnection = require('./utils/database');
router.get('/', function(req, res) {
createConnection(function(err, connection) {
// do whatever you want with your connection here
connection.release();
});
});
module.exports = router;
It will create a new connection every time you call connection.connect().
The connection is destroyed when either the program exits, or connection.end() is called. If you want to reuse the connection, you can put the connection logic in a separate module and then just export the connection itself, like this.
In a file called connection.js
var mysql = require("mysql");
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'password'
});
connection.connect();
module.exports = connection;
And then in any client file:
var connection = require("./connection.js");
connection.query('some query', callback);
Each file the requires connection.js will reuse the existing connection.
I'm completely new to nodejs + expressjs comming from php and I'm getting trouble how to export/include a var to my routes/users.js file.
on app.js I have:
//database connection
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbNodeExpress'
});
... some code
var user = require('./routes/user'); //here I include my routes/files (I dont know if it's right to include the routes here - for learning purposes it works for now)
... more code until starts the server
On my /routes/user.js
app = require('../app');
//var mysql = require('mysql');
var baseUrl = app.get('baseUrl');
app.get('/users_mysql', function(req, res){
connection.query('SELECT * FROM users', function(err, users){
res.json(users);
});
});
and I get the express error: 500 ReferenceError: connection is not defined
The connection works because if I move the content from users.js to app.js I can query the database.
My questions is how to inject the var connection to be used on routes/users.js
Any help / hint to understand this is very appreciated. Thanks in advance.
There are several ways you could do this. A couple solutions might be:
Create a resources.js file that creates and exports the connection. Then require() resources.js in every source file where you need it.
Pass the connection to your user route file. Something like this:
// app.js
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbNodeExpress'
});
require('./routes/user')(connection);
// routes/user.js
module.exports = function(connection) {
app.get('/users_mysql', function(req, res){
connection.query('SELECT * FROM users', function(err, users){
res.json(users);
});
});
};
create a database connector javascript file. as like database_connector.js
and require it when ever you want to have the connection pooled or the connection class availabel to your models. tip : you can also export config files like below or use barely values.
var mysql = require('mysql');
var config = require("./config");
function Connection() {
this.pool = null;
this.init = function() {
this.pool = mysql.createPool({
connectionLimit: config.poolSize,
host: config.host,
user: config.user,
password: config.password,
database: config.database,
debug:config.debug,
});
};
this.acquire = function(callback) {
this.pool.getConnection(function(err, connection) {
callback(err, connection);
});
};
console.log("connection"+this.pool);
}
module.exports = new Connection();