Where can I find the url or ip address of SQL Server Database [duplicate] - node.js

Is there any way I can get my Node.js app to communicate with Microsoft SQL?
I haven't seen any MS SQL drivers out there in the wild?
I'm putting a very simple app together and need to be able to communicate with an existing MS SQL database (otherwise I would have gone with mongoDB or Redis)

The original question is old and now using node-mssql as answered by #Patrik Šimek that wraps Tedious as answered by #Tracker1 is the best way to go.
The Windows/Azure node-sqlserver driver as mentioned in the accepted answer requires you to install a crazy list of prerequisites: Visual C++ 2010, SQL Server Native Client 11.0, python 2.7.x and probably also Windows 7 SDK for 64-bit on your server. You don't want to install all these GB's of software on your Windows Server if you ask me.
You really want to use Tedious. But also use node-mssql to wrap it and make coding a lot easier.
Update August 2014
Both modules are still actively maintained. Issues are responded on quite quickly and efficiently.
Both modules support SQL Server 2000 - 2014
Streaming supported since node-mssql 1.0.1
Update February 2015 - 2.x (stable, npm)
Updated to latest Tedious 1.10
Promises
Pipe request to object stream
Detailed SQL errors
Transaction abort handling
Integrated type checks
CLI
Minor fixes
This is plain Tedious:
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var config = {
server: '192.168.1.212',
userName: 'test',
password: 'test'
};
var connection = new Connection(config);
connection.on('connect', function(err) {
executeStatement();
}
);
function executeStatement() {
request = new Request("select 42, 'hello world'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
connection.close();
});
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log(column.value);
}
});
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
// In SQL Server 2000 you may need: connection.execSqlBatch(request);
connection.execSql(request);
}
Here comes node-mssql which has Tedious as a dependency. Use this!
var sql = require('mssql');
var config = {
server: '192.168.1.212',
user: 'test',
password: 'test'
};
sql.connect(config, function(err) {
var request = new sql.Request();
request.query("select 42, 'hello world'", function(err, recordset) {
console.log(recordset);
});
});

A couple of new node.js SQL server clients have just released recently. I wrote one called node-tds and there is another called tedious

We just released preview drivers for Node.JS for SQL Server connectivity. You can find them here:
http://blogs.msdn.com/b/sqlphp/archive/2012/06/08/introducing-the-microsoft-driver-for-node-js-for-sql-server.aspx

(duplicating my answer from another question).
I would recommend node-mssql, which is a nice wrapper for other connectors, the default being my previous choice (Tedious) bringing a bit nicer of an interface. This is a JavaScript implimentation, with no compilation requirements, meaning you can work in windows and non-windows environments alike.
Another option, if you don't mind bringing in .Net or Mono with a binary bridge would be to use edge.js. Which can be very nice if you want to leverage .Net libraries in node.js
node-tds is abandoned, node-odbc doesn't work with windows, and the MS node-sqlserver driver doesn't seem to work on non-windows (and has some goofy requirements).

There is another module you can use - node-mssql. It uses other TDS modules as drivers and offer easy to use unified interface. It also add extra features and bug fixes.
Extra features:
Unified interface for multiple MSSQL drivers
Connection pooling with Transactions and Prepared statements
Parametrized Stored Procedures for all drivers
Serialization of Geography and Geometry CLR types
Smart JS data type to SQL data type mapper
Support both Promises and standard callbacks

You could maybe use node-tds.js:
An exciting implementation of the TDS protocol for node.js to allow communication with sql server...
USAGE:
var mssql = require('./mssql');
var sqlserver = new mssql.mssql();
sqlserver.connect({'Server':__IP__,'Port':'1433','Database':'','User Id':'','Password':''});
var result = sqlserver.execute("SELECT * FROM wherever;");

TSQLFTW - T-SQL For The WIN(dows) - by Fosco Marotto
https://github.com/gfosco/tsqlftw
It is a C# and ADO .NET managed code solution, with a C++ wrapper that Node.js can import and work with.
If you know .NET you could try WCF Data Services (ADO.NET Data Services); write an WCF app for data access and use odata (REST on steroids) to interact with the database
WCF Data Services: http://msdn.microsoft.com/en-us/data/bb931106
OData: http://www.odata.org/
If you are into SOA and use SQL Server 2005 you could check out the Native XML Web Services for Microsoft SQL Server 2005
http://msdn.microsoft.com/en-us/library/ms345123(v=sql.90).aspx
You could access SQL Server as a web service (HTTP, SOAP)

Microsoft (The Windows Azure Team) just released a node driver for SQL SERVER.
It has no package for npm yert, as far as I know, but it is open sourced. And the accepting community contribution too.
https://github.com/WindowsAzure/node-sqlserver
Introduction blog post here:
http://blogs.msdn.com/b/sqlphp/archive/2012/06/08/introducing-the-microsoft-driver-for-node-js-for-sql-server.aspx

I'd suggest taking a look at Prisma. We just (October 2020) announced preview support for SQL Server.
Prisma is an ORM that puts the emphasis on type-safety and developer experience. Unlike traditional ORMs that typically map tables to classes, Prisma maps queries to types (in TypeScript) and returns plain objects from queries.
To get started with Prisma and SQL Server check out this example and start from scratch guide in the docs.

If you are running on .NET look at entityspaces.js at, we are creating an entire universal ORM for Node.js that will not require a WCF JSON service ... https://github.com/EntitySpaces/entityspaces.js
If you are using MSFT backend technology you could use it now, however, we are creating a universal Node.js ORM and will have more information on that soon

There is an update from Microsoft. Here is a series of blog posts (part 1 and part 2).

Node.js SQL Server drivers seem very immature - there's a mish-mash of different projects with varying dependencies, performance, and levels of completeness, none of which inspire confidence.
I'd propose using edge-sql. This leverages .NET's mature database driver ecosystem, and depends only on .NET (a no-brainer if you are running node on Windows - if not there is Mono, but I have not tried that).
Here is a node example (server.js) using edge-sql (note you need to put your connection string into an environment variable as per edge-sql docs):
var edge = require('edge');
// edge-sql has built in support for T-SQL / MSSQL Server
var getData = edge.func('sql', function () {/*
select top 10 * from sometable
*/
});
getData(null, function (error, result) {
if (error) throw error;
console.log(result);
});
You can also leverage Edge.js with .NET to access other databases, such as Oracle. I have given an example of that approach here.

The status as of May 2016 is as follows.
The official Microsoft SQL Driver for Node, called node-sqlserver, has not been updated for a number of years.
There is a new fork on this called node-sqlserver-v8 that works with Node Versions 0.12.x. and >= 4.1.x. This fork also has pre-compiled binaries for x64 and x86 targets.
The package is available on NPM as msnodesqlv8.
I recommend this package because it is lightweight (has no dependencies) and it is the only one that works with all recent version of SQL Server, including SQL LocalDB.

Now (2016) you can use Sequelize ORM that supports:
MySQL / MariaDB,
PostgreSQL
SQLite
Microsoft SQL Server
It is widely used according to its Github's stars.

that link details only a sql 2000 solution, not sql 2005 nor sql 2008, and also that code only allow sending sql text, and does not allow the execution of stored procedures.
The real solution would be to install node JS on a linux server, or on a virtual linux server on a windows machine, and then go to microsoft web site and download the JDBC java drivers and install those microsoft ms sql java jdbc drivers on either the linux server or linux virtual server.

Related

Azure Java SDK for MySQL/PostgreSQL databases?

So, Azure has three variants of SQL services:
SQL Database: https://azure.microsoft.com/en-in/services/sql-database/
MySQL: https://azure.microsoft.com/en-in/services/mysql/
PostgreSQL: https://azure.microsoft.com/en-in/services/postgresql/
I can see that there is a Java SDK for the first one. Are there any Java SDKs available for the MySQL/Postgres service APIs?
Maybe this question isn't fit for SO, but wasn't able to get any response on Github issues, so asking it here.
Looking at the source code here, I believe there are no SDKs for MySQL & Postgres database management in Java as of today.
Since SDKs are essentially a wrapper over REST API, one option for you would be to implement REST API yourself till the time support for these come into SDK.
Here are the links to the REST APIs for MySQL & Postgres:
MySQL: https://learn.microsoft.com/en-us/rest/api/mysql/
Postgres: https://learn.microsoft.com/en-us/rest/api/postgresql/
Azure Java SDK version 1.33.1 doesn't have an inbuilt MySQL management client yet. However, you can use Maven dependency mentioned here
The entry class should be MySQLManager.
Here is a sample code that I have written to create a MySQL server instance using the same client.
#Override
public Server createMySQLServer(AzureTokenCredentials credential,
AzureMySqlModel model) {
if (credential == null || model == null)
return null;
Server server = null;
if (model.validate()) {
try {
ServerPropertiesForDefaultCreate defaultProp = new ServerPropertiesForDefaultCreate();
ServerPropertiesForCreate withVersion = defaultProp.withAdministratorLogin(
model.getAdministratorLogin()).withAdministratorLoginPassword(
model.getAdministratorPassword()).withVersion(
model.getServerVersion());
server = MySQLManager.configure().withLogLevel(
LogLevel.BODY).authenticate(credential,
credential.defaultSubscriptionId()).servers().define(
model.getServerName()).withRegion(
model.getRegion()).withExistingResourceGroup(
model.getResourceGroup()).withProperties(
withVersion).create();
} catch (Exception ex) {
log.error("Error creating MySQL server {}", ex.getMessage());
}
}
return server;
}
AzureMySqlModel is just a custom Java POJO to get the required details for creating a MySQL server.
Nowadays, both of postgres and mysql was added to Azure SDK
Here, I want to note that both of them have flexible server and those also have different dependencies. Don't repeat my mistake, above dependencies does not work flexible servers.
Akash's answer is also right, but this dependency will become deprecated from next year.

sails.js - I want to add DB connection dynamically after sails lift

During sails lift I don't yet have all the connection information for my DB.
Is there a way to either have config values dependent on promises or dynamically create a connection after sails lift has completed?
I would obviously have to add a policy or hook to handle requests to routes needing the model if it wasn't available yet, but at this point I don't see how to even let the sails lift until I already know the connection info (it must be in the configs).
I'm hoping I'm missing a way to dynamically create connections and wire models to them.
Update: In Sails v1.0 / Waterline v0.13, this can be accomplished by accessing the stateless, underlying driver; e.g. sails.getDatastore().driver. This can be used in any database adapter that supports the new stateless driver interface, including MySQL, PostgreSQL, and MongoDB.
Prior to Sails v1.0, this was not officially supported in Sails or Waterline directly, but depending on your use case there are a couple of good solutions for this. If your use case is a handful of dynamic connections for the purpose of development (e.g. in an auto-reload plugin), and you're willing to live on the edge, you can take advantage of a private API as an immediate-term workaround: sails.hook.orm.reload(). However you definitely don't want to use that in production since it literally flushes the entire ORM.
If you are going to be dealing with a larger number (let's say > 10 unique configurations) of runtime-dynamic datastore configurations during the lifetime of the running Node process, that's a different story. In that case, I would recommend using the relevant raw driver (e.g. https://github.com/felixge/node-mysql) to summon/release those dynamic connections from a pool directly via a service. You can still use your normal models in your app for connections which are static-- you will just be best off implementing dynamic database connections separately in your service. For example, if you were building a hosted version of phpMyAdmin you might use a lower-level NPM package to dynamically fetch information about users' tables, but you'd still probably want to have Account and Database models that refer to tables/collections stored in your own database.
A more integrated solution for Sails is in the works. This ability to tap into the raw connection lifecycle and access it from userland is a prerequisite for built-in transaction support, which is something we expect to land in Sails/Waterline some time in the second half of 2016. In the mean time, if you encapsulate your logic to summon/release connections via service methods as suggested above, you'll have a working solution for now and your business logic should be more or less future proof (when you upgrade, you'll just need to swap out the implementation in your service). Hope that helps!
Yes; two things in sails.js allow you to do this. One currently exists, and one is upcoming.
https://github.com/sgress454/sails-hook-autoreload. This module watches for config file changes on disk and will re-load your ORM models when a file changes.
I am working on this exact feature right now, and my plan is to publish my work at the end of next week. I agree that it will be very useful.
The API will allow you to define new Models and Connections in the database on the fly. sails.js lifecycle callbacks handle updating the ORM and adapters and so forth. It is event-based and will allow you to manually fire events to update the ORM/Connections, like so:
sails.emit('hook:dynamic-orm:reload')
Is this what you need?
I have found a workaround for MySql DB
Important: In my case, I will be changing database but all database would have the same schema only difference is in their name and data they contain and make sure to add any error handling you need
In config/connection.js --------
disable Pooling
mysql_database: {
adapter: 'sails-mysql',
host: 'localhost',
user: 'root', //optional
password: '12345', //optional
database: 'db1', //optional
pool: false
},
Now navigate to
node_modules/sails-mysql/lib/connections/spawn.js
Add connectionObject.config = sails.SwitchDbConfig
connectionObject.config = sails.SwitchDbConfig
var conn = mysql.createConnection(connectionObject.config);
conn.connect(function (err) {
afterwards(err, conn);
});
Now Finally Set sails.SwitchDbConfig form anywhere (service , controller ,etc)
as
sails.SwitchDbConfig = {
pool: false,
connectionLimit: 5,
waitForConnections: true,
adapter: 'sails-mysql',
host: 'localhost',
user: 'root',
password: '12345',
database: sails.DB_NAME,
identity: 'mysql_database'
}
And at last if you find something wrong for needs to be updated .... please ping

Limit MongoClient to read only operations

Is it possible to connect to MongoDB in a read-only mode?
I'm currently using the driver for Node.js to create a new client with MongoClient.connect:
require('mongodb').MongoClient.connect(url, {
// options object
}, function(err, client) {
// ...
});
I don't see anywhere in the docs how to create a client in read-only mode.
It is possible? how?
Background:
I'm building an app which connects to a MongoDB. Other developers in my team extend this app with plugins that consume data. A plugin is supplied with a client object to access the databse. I want to prevent other developers from accidentally making changes to the database.
One of the most clever workarounds for this scenario requires the usage of replica set. Simply connect only to one of the secondary node(s) will prevent write operation and achieve a read-only behaviour.

Accessing .mdb files through nodejs

I want to Access .mdb files and manipulate like insert / update using nodejs
Please suggest a library that would suite the need.
Thanks.
Slightly different but node-adodb worked well for me for .accdb files:
https://www.npmjs.org/package/node-adodb
// Get the adodb module
var ADODB = require('node-adodb');
ADODB.debug = true;
// Connect to the MS Access DB
var connection = ADODB.open('Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\dbs\\my-access-db.accdb;Persist Security Info=False;');
// Query the DB
connection
.query('SELECT * FROM [TestTable];')
.on('done', function (data){
console.log('Result:'.green.bold, data);
})
This article describes the process for connecting PHP to an Access .mdb database:
http://www.sitepoint.com/using-an-access-database-with-php/
The process for Node.js is quite similar - it's just another ODBC data source.
You'll need a node ODBC package, such as:
https://github.com/wankdanker/node-odbc
https://github.com/markdirish/node-odbc/
Then you'll need to format your ODBC connection string. eg.
"DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=MyDatabase; Uid=; Pwd=;"
My suggestion is OWIN module which is currently developed as Edge.js by Mr Tomasz Janczuk.

Cloud Foundry - node.js - MySQL

Please help me on how to connect/bind to mysql services of cloud foundry using node.js and node-mysql module?
In cloud foundry we can connect/bind to mysql services and cloud foundry supports applications of type spring, node.js, etc,...
I have successfully develpoed a spring application and hosted in cloudfoundry and able to connect/bind to mysql services of cloudfoundry. Also I could able to connect to mysql running locally using node-mysql module.
But I want to connect/bind to mysql services of cloud foundry using node.js and node-mysql module and there are no examples related to the same. Is it possible to do this?
Any help in this regard is greatly appriciated.
Thank you.
Regards,
Kishan.G
I think the first thing to note is that CloudFoundry will very shortly support the automatic reconfiguration of Node.JS applications much in the same vain as we currently do with Rails. This means being able to develop a Node.JS app locally that uses MySQL and when deploying it to CloudFoundry it will automatically be reconfigured to use a bound service instead.
Until that feature is live, which as I said won't be long, you will have to use the VCAP environment variables to configure the connection at runtime. There is a pretty good example of this approach being used with Node.JS here - http://www.mihswat.com/2011/05/04/getting-started-with-cloud-foundry-using-a-node-js-and-mongodb-application/ albeit for MongoDB, the approach is exactly the same.
The part to pay particular attention to is where the author reads the environment in to a hash with the following code;
var boundServices = process.env.VCAP_SERVICES
? JSON.parse(process.env.VCAP_SERVICES) : null;
and then uses them to initialise a connection;
if (boundServices == null) {
db = mongoose.connect('mongodb://localhost/analytics');
} else {
credentials = boundServices['mongodb-1.8'][0]['credentials'];
db = mongoose.createConnection("mongo://"
+ credentials["username"]
+ ":" + credentials["password"]
+ "#" + credentials["hostname"]
+ ":" + credentials["port"]
+ "/" + credentials["db"]);
}
If you need any further pointers, then let me know.

Resources