How to connect openshift Phpmyadmin database using Nodejs Server? - node.js

How to connect "openshift phpmyadmin database" using nodejs server
Below is my code ... I am not getting result from the database ...
log :
Success{"fieldCount":0,"affectedRows":0,"insertId":0,"serverStatus":2,"warningCo
unt":0,"message":"","protocol41":true,"changedRows":0}
var connection = mysql.createConnection({
OPENSHIFT_NAMMAOORU_DB_HOST :'127.4.188.2',
OPENSHIFT_NAMMAOORU_DB_PORT :'3306',
OPENSHIFT_NAMMAOORU_DB_USERNAME:'adminfxxxxx',
OPENSHIFT_NAMMAOORU_DB_PASSWORD:'xxxxxxxxx',
OPENSHIFT_NAMMAOORU_DB_URL:'mysql://adminxxxx:xxxxxxx#127.4.188.2:3306',
//database:'nammaooru'
});
connection.connect(function(err,success){
if (err) {
throw err;
console.log("Error"+JSON.strinerr);
}
else
{
console.log("Success"+JSON.stringify(success));
}
});
app.get('/city',function(req,res){
try{
//var id = req.query.id;
/*var t=req.query.id;
console.log(t);
*/ /* var data = {
"error":1,
"Books":""
};*/
console.log(req.params.cityid);
var t=1;
connection.query("SELECT * from city",function(err, rows, fields){
console.log("success"+JSON.stringify(rows));
//console.log("success"+JSON.stringify(fields));
//console.log(JSON.stringify(rows));
res.send(JSON.stringify(err));
//console.log("success"+JSON.stringify(err));
});
}
catch(e)
{
console.log(e);
}
});
Local Rest url http://localhost:8000/city
{ code: "ER_NO_DB_ERROR", errno: 1046, sqlState: "3D000", index: 0 }

I don't think you are creating the mysql connection properly:
var connection = mysql.createConnection({
host: '127.4.188.2',
user: 'adminfxxxxx'',
password: 'xxxxxxxxx',
port: 3306
});

Try this just add database name as below
var connection = mysql.createConnection({
host :'127.4.188.2',
port :'3306', // if this doesn't work try removing port once
user:'adminfxxxxx',
password:'xxxxxxxxx',
database:'xxxxxxxxx', //specify database Name

Related

sql.Connection is not a constructor [nodejs expressjs and SqlServer] ---

I am trying to write a backend API in node and express JS to connect to SQL Server[with windows authentication] and fetch data. The error message is --
const poolPromise = new sql.Connection(config)
TypeError: sql.Connection is not a constructor
The relevant config file code is dbConfig.js :
const sql = require('msnodesqlv8')
const config = {
database: 'ApiDemoDB',
server: '.\\SQLEXPRESS',
driver: 'msnodesqlv8',
options: {
trustedConnection: true
}
}
const poolPromise = new sql.Connection(config) <-------this line error
.connect()
.then(pool => {
console.log('Connected to MSSQL')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config!: ', err))
module.exports = {
sql, poolPromise
}
What is the meaning of this error message? sql.Connection is not supposed to take any parameter[config]? I don't get it, what am I supposed to do differently here? What additional code changes do I have to make in order to get this working? Can you please help me solve this problem so that the API can connect to the mssql database? As you can see, as of now I have very little code. Barebones.
Thanking you in advance.
*********************************** EDIT ***********************************
I have changed the code around quite a bit.
My dbconfig.js file is now as:
const sql = require('mssql');
const msnodesqlv8=require('msnodesqlv8');
var dbconfig = {
server: 'localhost',
database: 'ApiDemoDB',
driver: 'msnodesqlv8',
options: {
enableArithAbort:true,
trustedConnection: true,
instancename:'SQLEXPRESS'
},
port:1433
}
module.exports=dbconfig;
And then a separate dbconnect.js file as:
var sql = require("mssql/msnodesqlv8")
var dbConfig = require("./dbConfig")
var dbConnect = new sql.connect(dbConfig,
function(err)
{
if(err){
console.log("Error while connecting to database: " + err)
}else{
console.log("connected to database: " + dbConfig.server)
}
}
)
module.exports = dbConnect
Now, the error that I have is ->
Error while connecting to database: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
What does this even mean. It's pointing to the dbconfig file, but what changes to be written there, can you suggest me? Thanks

Moving data from nodejs console to SQL Server

I am very new to node.js. Using the following code I am able to retrive data from the wesbite intrino into console.
var https = require("https");
var username = "********";
var password = "********";
var auth = "Basic " + new Buffer(username + ':' +
password).toString('base64');
var request = https.request({
method: "GET",
host: "api.intrinio.com",
path: "/companies?ticker=AAPL",
headers: {
"Authorization": auth
}
}, function (response) {
var json = "";
response.on('data', function (chunk) {
json += chunk;
});
response.on('end', function () {
var company = JSON.parse(json);
console.log(company);
});
});
request.end();
And the result is as follows:-
My question is: how do I transfer this data into SQL Server? I tried watching a few tutorials and videos. But I was not able to exactly understand how it works.
Thanks in advance.
This is a very broad question. Connecting MS-SQL server from node usually uses tedious package. You can directly use this package to insert data as described in https://learn.microsoft.com/en-us/sql/connect/node-js/step-3-proof-of-concept-connecting-to-sql-using-node-js
Following is a snippet from the above link.
var Connection = require('tedious').Connection;
var config = {
userName: 'yourusername',
password: 'yourpassword',
server: 'yourserver.database.windows.net',
// If you are on Azure SQL Database, you need these next options.
options: {encrypt: true, database: 'AdventureWorks'}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement1();
});
var Request = require('tedious').Request
var TYPES = require('tedious').TYPES;
function executeStatement1() {
request = new Request("INSERT SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) OUTPUT INSERTED.ProductID VALUES (#Name, #Number, #Cost, #Price, CURRENT_TIMESTAMP);", function(err) {
if (err) {
console.log(err);}
});
request.addParameter('Name', TYPES.NVarChar,'SQL Server Express 2014');
request.addParameter('Number', TYPES.NVarChar , 'SQLEXPRESS2014');
request.addParameter('Cost', TYPES.Int, 11);
request.addParameter('Price', TYPES.Int,11);
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log("Product id of inserted item is " + column.value);
}
});
});
connection.execSql(request);
}
But using an ORM is the best practice. sequelize is one of the best in the node community.
$ npm install --save sequelize
$ npm install --save tedious // MSSQL
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mssql'
});
You must go through either of these modules documentation to understand better.

Pool getConnection undefined

The problem is when I tried the pool connection via variable I'm getting following error
TypeError: sourCon.sourceDBConnection.getConnection is not a function
but if I try the normal connection it's fine.
The code is as follows:
File. ./db/source_db.js
module.exports =
{
sourceDBConnection: function () {
return mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : '',
database : 'testdb'
});
}
};
File: app.js
app.get('/report-url', function (req, res) {
corporateModel.DetailReport(dateTime(),request);
})
File. ./models/corporate.js
var sourCon = require("../common_config/source_db");
module.exports =
{
DetailReport: function (dateTime,request,Q) {
var whereTripQueryAppend = "";
sourCon.sourceDBConnection.getConnection(function(err, finConnection) {
/* Get the last inserted ID */
finConnection.query("SELECT student_id FROM studen LIMIT 1", function (error, lastResults, fields) {
/* some process here */
})
})
})
}
Do you know why it works for the normal connection and it's not working for the pool connections? Also if I defined the connection in the same file it works fine. AS
File. ./models/corporate.js
var sourceDBConnection = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : '',
database : 'testdb'
});
var sourCon = require("../common_config/source_db");
module.exports =
{
DetailReport: function (dateTime,request,Q) {
var whereTripQueryAppend = "";
sourceDBConnection.getConnection(function(err, finConnection) {
/* Get the last inserted ID */
finConnection.query("SELECT student_id FROM studen LIMIT 1", function (error, lastResults, fields) {
/* some process here */
})
})
})
}

How to share connection pool between modules in node.js?

I have a little or no knowledge at how to properly implement postgres connection pool in node.js modules.
My question is : Is it problem when I am creating new Pool in every module where I need a connection to pg ?
Is there a way to create pool globally for a whole app ?
Thanks.
Define the pool in a file say pgpool.js
var pg = require('pg');
var pool;
var config = {
user: 'foo',
database: 'my_db',
password: 'secret',
port: 5432,
max: 10,
idleTimeoutMillis: 30000,
};
module.exports = {
getPool: function () {
if (pool) return pool; // if it is already there, grab it here
pool = new pg.Pool(config);
return pool;
};
Use it like this:
var db = require('./a/path/to/pgpool.js');
var pool = db.getPool();
I would suggest to not export the pool, but a function that provides a connection to it. Using promise-mysql
var mysql = require('promise-mysql');
var connectionPool = mysql.createPool({
host : "127.0.0.1",
user : '******',
password : '******',
database : '******',
port : '3306'
});
module.exports={
getConnection: function(){
return new Promise(function(resolve,reject){
connectionPool.getConnection().then(function(connection){
resolve(connection);
}).catch(function(error){
reject(error);
});
});
}
}
I have made a simple blog post about MySQL pool sharing, where you can read more

mongodb + node connection string

I'm having trouble connecting mongodb to my local machine. I'm new at this and can't seem to figure it out from the docs or other stackoverflow posts.
I have a database.js file, and I think my connection string is wrong:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost');
// I've tried this too:
// mongoose.connect('mongodb://localhost/test');
// mongoose.connect('mongodb://localhost:8080/test');
module.exports = {
'url' : 'mongodb://localhost:27017/test'
}
I've got mongod running in one tab and shows 4 connections open - I don't know if it's this or the connection string.
Then in a 2nd tab, I've connected to a db called "test".
Lastly there's a very simple view. When I navigate to localhost:8080 (where process.env.PORT || 8080 is pointing to in server.js), it doesn't connect.
Try this
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');//Here test is my database
var Cat = mongoose.model('Cat', { name: String });
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
if (err) {
console.log(err);
} else {
console.log('meow');
}
});
Here is configuration file
{
"db": {
"connection": "mongodb://localhost",
"name": "testdb"
}
}
Here is usage in code:
var dbUrl = config.get('db:connection') + '/' + config.get('db:name');
var db = mongoose.connection;
mongoose.connect(dbUrl, function(err) {
//your stuff here
});
Hope, it helps.
P.S. Could you please provide how you catch no connection to db?

Resources