nodejs mssql insert with parameters - sql-server

I'm new to NodeJS where I'm trying to insert into a table with parameters so I can avoid SQL Injection and just escape any characters that might cause issues.
So I currently have an application that insert into the data without parameters.
Here is what I have so far:
var fs = require('fs');
var sql = require('mssql');
var LINQ = require("node-linq").LINQ;
const simpleParser = require('mailparser').simpleParser;
var Client = require('yapople').Client;
var client = new Client({
hostname: 'xxxxxx',
port: 995,
tls: true,
mailparser: true,
username: 'xxxxx',
password: 'xxxxx'
});
const config = {
user: 'xxxxxxx',
password: 'xxxxx',
server: 'xxxxx\\',
port: 'xxxxx'
database: 'xxxxxx',
options: {
instanceName: 'xxxxx'
}
};
(async function () {
try {
let pool = await sql.connect(config)
//Get all current emails
let emails = await pool.request()
.query('select uid from email')
//Get uids only
var uids = new LINQ(emails.recordset)
.Select(function(email) {return email.uid;})
.ToArray();
//Get all emails
client.connect(function() {
client.retrieveAll(function(err, messages) {
messages.forEach(function(message) {
//Check if the message exists in our database already.
var messageId = message.messageId;
var emailExists = new LINQ(uids)
.Where(x=>x == messageId).ToArray();
//If the message do not exists then add them to the database
if(emailExists.length == 0){
var sentDate = new Date(message.date).toISOString();
var subject = message.subject;
var body = message.text;
var mailAddress = "";
var mailAddressName = "";
if(message.from.length > 0){
mailAddress = message.from[0].address;
mailAddressName = message.from[0].name;
}
const request = pool.request();
request.input('uid', sql.VarChar, messageId);
request.input('mail_address', sql.VarChar, mailAddress);
request.input('mail_address_display_name', sql.VarChar, mailAddressName);
request.input('subject', sql.VarChar, subject);
request.input('body', sql.VarChar, body);
request.input('sent_date', sql.DateTime, sentDate);
request.input('created_by', sql.VarChar, 'system');
let result = await request.query('INSERT INTO email(uid, mail_address, mail_address_display_name, subject, body, sent_date, created_by) OUTPUT INSERTED.ID values (#uid, #mail_address, #mail_address_display_name, #subject, #body, #sent_date, #created_by)', (err, result) => {
console.dir(result)
})
}
});
client.quit();
})
});
} catch (err) {
console.log(err);
// ... error checks
}
})()
I was looking at prepared statements but I could not get that working.
Here is what I was attempting with prepared statements
const ps = new sql.PreparedStatement();
ps.input('uid', TYPES.VarChar);
ps.input('mail_address', TYPES.VarChar);
ps.input('mail_address_display_name', TYPES.VarChar);
ps.input('subject', TYPES.VarChar);
ps.input('body', TYPES.VarChar);
ps.input('sent_date', TYPES.DateTime);
ps.input('created_by', TYPES.VarChar);
ps.prepare('INSERT INTO email(uid, mail_address, mail_address_display_name, subject, body, sent_date, created_by) ' +
' OUTPUT INSERTED.email_id VALUES (#uid, #mail_address, #mail_address_display_name, #subject, #body, #sent_date, #created_by)',
err => {
ps.execute({
uid: messageId,
mail_address: mailAddress,
mail_address_display_name: mailAddressName,
subject: subject,
body: body,
sent_date: sentDate,
created_by: 'system'
}, (err, result) => {
// ... error checks
ps.unprepare(err => {
var x =1;
})
})
}
)

You can use the connection pool request object to add parameters, e.g.
const request = pool.request()
request.input('myval', sql.VarChar, 'value')
request.query('insert into testtable (somecolumn) values (#myval)', (err, result) => {
console.dir(result)
})

Related

Flutter sqflite file is not a database

I'm trying to backup and restore a sqlite database using flutter. The database file is backed up on a server via a php api; same for the restore.
The error returned
Unhandled Exception: DatabaseException(Error Domain=FMDatabase Code=26 "file is not a database" UserInfo={NSLocalizedDescription=file is not a database}) sql 'SELECT * FROM journal' args []
Here is my functions to backup on server and restore in the app
BACKUP FUNCTION
static exportDB(bool isWithMessage) async {
if(int.parse(Common.storage.read('user')['abonnement'])==1)
{
String path = await getDatabasesPath();
path += '/jonadatabase';
// Create an instance of GetConnect
final GetConnect _connect = GetConnect(
timeout: const Duration(seconds: 10),);
final FormData _formData = FormData({
'fichier': MultipartFile(File(path), filename: 'jonadatabase'),
'user_id': Common.storage.read('user')['id']
});
Map<String, String> headers = {
'Authorization': 'Bearer ${Common.storage.read('user')['token']}'
};
try {
final Response res = await _connect.post(
'${Common.apiLink}/fichier/${Common.storage.read('user')['id']}',
_formData, headers: headers);
if (res.body['status'].toString() == 'true') {
if (isWithMessage == true) {
Get.back();
Common.customSnackbar(
'Info', "DBExportSuccessfully".tr, Icons.check_circle,
CustomColor.primaryColor);
}
} else {
Get.back();
Common.customSnackbar(
'error'.tr, "errorWhenExportDB".tr, Icons.check_circle,
CustomColor.primaryColor);
}
} catch (err) {
// Handle errors
print(err);
}
}
else
{
if(isWithMessage == true) {
Common.customSnackbar(
'error'.tr, "upgradeToEverywherePlan".tr, Icons.info,
CustomColor.primaryColor, sec: 7);
Get.defaultDialog(title: '', content: Pricing(type: 'renew'));
}
}}
RESTORE FUNCTION
static loadDB() async {
var url = "${Common.webLink}/uploads/database/";
var filename = 'copy';
await Common.downloadFile(url, filename);
var dbPath = join(await getDatabasesPath(),'jonadatabase');
ByteData data = await rootBundle.load(join(await getDatabasesPath(), 'copy'));
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(dbPath).writeAsBytes(bytes);
MainController.to.database = await openDatabase(dbPath);
if(Common.storage.hasData('user')) {
Common.storage.read('user')['fichier'] = 'copy';
}
}

Trying to connect my application with SQL Server using sql_server_socket. In SqlConnection.dart the guinness package's version is not specified right

// Copyright (c) 2015, <your name>. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
library sql_server_socket_test;
import '../lib/sqlconnection.dart';
import '../lib/table.dart';
import '../lib/sqlformats.dart';
import 'dart:async';
//Error occurs here(Couldn't get pub because of wrong version specification)
import "package:guinness/guinness.dart";
void main()
{
defineSpecs().then((_){});
}
Future defineSpecs() async
{
/// creates a common database where to perform all tests
var conn = new SqlConnection("Server=localhost\\SQLEXPRESS;Database=master;Trusted_Connection=yes;");
//var conn = new SqlConnection("Server=DEVIL\\SQLEXPRESS;Database=master;User Id=sa;Password=;");
await conn.open();
await conn.execute("IF EXISTS (SELECT name FROM master.sys.databases WHERE name = 'sql_server_socket_test_db') DROP DATABASE sql_server_socket_test_db");
await conn.execute("CREATE DATABASE sql_server_socket_test_db");
await conn.execute("USE sql_server_socket_test_db");
await conn.execute("CREATE TABLE Customers (Id INT IDENTITY PRIMARY KEY, Name VARCHAR(64), Age INT, Born DATETIME, HasWebSite BIT NOT NULL)");
await conn.execute("INSERT INTO Customers (Name, Age, HasWebSite) VALUES ('Bob' ,33, 0)");
await conn.execute("INSERT INTO Customers (Name, Age, HasWebSite, Born) VALUES ('Tom' ,42, 1, ${sqlDate(new DateTime(1972,05,03))})");
await conn.execute("INSERT INTO Customers (Name, Age, HasWebSite) VALUES ('Mary',18, 1)");
await conn.close();
conn = new SqlConnection("Server=localhost\\SQLEXPRESS;Database=sql_server_socket_test_db;Trusted_Connection=yes;");
//conn = new SqlConnection("Server=DEVIL\\SQLEXPRESS;Database=sql_server_socket_test_db;User Id=sa;Password=;");
describe("SQL formatting functions", ()
{
describe("sqlDate()", ()
{
it("returns a SQL formatted date", ()
{
var d = sqlDate(new DateTime(1980,5,3));
expect(d).toEqual("CONVERT(DATETIME,'1980-05-03 00:00:00.000',102)");
});
});
describe("sqlBool()", ()
{
it("converts true and false into 1 and 0", ()
{
expect(sqlBool(false)).toEqual("0");
expect(sqlBool(true )).toEqual("1");
});
});
describe("sqlString()", ()
{
it("sqlString() formats a string to SQL, keeping care of single quotes", ()
{
expect(sqlString("ONE'TWO''THREE'''")).toEqual("'ONE''TWO''''THREE'''''''");
});
});
});
// TODO connection tests (ports/service running etc)
describe('SqlConnection methods', ()
{
beforeEach(() async
{
await conn.open();
});
afterEach(() async
{
await conn.close();
});
describe("execute()", ()
{
it("returns the number of rows effected", () async
{
var n = await conn.execute("UPDATE Customers SET HasWebSite=1 WHERE HasWebSite=1");
expect(n).toEqual(2);
});
it("does UPDATE commands correctly when not changing anything", () async
{
var n = await conn.execute("UPDATE Customers SET HasWebSite=1 WHERE HasWebSite=1");
expect(n).toEqual(2);
});
it("returns 0 when nothing done", () async
{
var n = await conn.execute("UPDATE Customers SET HasWebSite=1 WHERE 0=1");
expect(n).toEqual(0);
});
it("does UPDATE commands correctly", () async
{
var n = await conn.execute("UPDATE Customers SET Name='Bill' WHERE Name='Bob'");
expect(n).toEqual(1);
var n1 = await conn.queryValue("SELECT COUNT(*) FROM Customers WHERE Name='Bob'");
var n2 = await conn.queryValue("SELECT COUNT(*) FROM Customers WHERE Name='Bill'");
expect(n1).toEqual(0);
expect(n2).toEqual(1);
n = await conn.execute("UPDATE Customers SET Name='Bob' WHERE Name='Bill'"); // reverts back
expect(n).toEqual(1);
});
});
describe("queryValue()", ()
{
it("returns null when querying empty rows", () async
{
// no customers named 'Mark'
var n = await conn.queryValue("SELECT Name FROM Customers WHERE Name='Mark'");
expect(n,null);
});
it("returns an integer value from query", () async
{
// Mary's Age is 18
var age = await conn.queryValue("SELECT Age FROM Customers WHERE Name='Mary'");
expect(age,18);
});
it("returns a boolean from query", () async
{
// Mary has a web site
var bit = await conn.queryValue("SELECT HasWebSite FROM Customers WHERE Name='Mary'");
expect(bit,true);
});
it("returns a String from query", () async
{
// Bob does not have a website
var name = await conn.queryValue("SELECT Name FROM Customers WHERE HasWebSite=0");
expect(name,"Bob");
});
it("returns null when queried field is null", () async
{
// First customer does not have a date
var born = await conn.queryValue("SELECT Born FROM Customers");
expect(born,null);
});
it("returns a DateTime from query", () async
{
var tomsborn = await conn.queryValue("SELECT Born FROM Customers WHERE Name = 'Tom'");
expect(tomsborn is DateTime).toEqual(true);
expect(tomsborn).toEqual(new DateTime(1972,05,03));
});
});
describe("querySingle()", ()
{
it("returns null when querying empty rows", () async
{
// no customers named 'Mark'
var n = await conn.querySingle("SELECT Name FROM Customers WHERE Name='Mark'");
expect(n).toEqual(null);
});
it("returns a row from query", () async
{
// tom's row
var row = await conn.querySingle("SELECT * FROM Customers WHERE Name='Tom'");
expect(row is Map).toEqual(true);
expect(row).toEqual({ "Id": 2, "Name": 'Tom' , "Age": 42, "HasWebSite": true, "Born": new DateTime(1972,05,03) });
});
});
describe("query()", ()
{
it("returns an empty List when querying empty rows", () async
{
// no customers named 'Mark'
var q = await conn.query("SELECT Name FROM Customers WHERE Name='Mark'");
expect(q).toEqual([]);
});
it("returns rows from query", () async
{
var q = await conn.query("SELECT Name, Age, HasWebSite, Born FROM Customers ORDER BY Id");
expect(q is List).toEqual(true);
expect(q.length).toEqual(3);
expect(q).toEqual(
[
{ "Name": 'Bob' , "Age": 33, "HasWebSite": false, "Born": null },
{ "Name": 'Tom' , "Age": 42, "HasWebSite": true, "Born": new DateTime(1972,05,03) },
{ "Name": 'Mary', "Age": 18, "HasWebSite": true, "Born": null }
]);
});
});
describe("queryTable()", ()
{
it("when result is empty, returns no rows and filled column info", () async
{
// no customers named 'Mark'
var table = await conn.queryTable("SELECT Name FROM Customers WHERE Name='Mark'");
expect(table.rows.length).toEqual(0);
expect(table.columns.length).toEqual(2); // Primary key Id is always included
});
it("returns a full datased", () async
{
// no customers named 'Mark'
var table = await conn.queryTable("SELECT Id, Name, Age, HasWebSite, Born FROM Customers ORDER BY Id");
expect(table.tableName).toEqual("Customers");
expect(table.rows.length).toEqual(3);
expect(table.columns.length).toEqual(5);
expect(table.rows).toEqual(
[
{ "Id": 1, "Name": 'Bob' , "Age": 33, "HasWebSite": false, "Born": null , "_originalIndex": 0 },
{ "Id": 2, "Name": 'Tom' , "Age": 42, "HasWebSite": true, "Born": new DateTime(1972,05,03) , "_originalIndex": 1 },
{ "Id": 3, "Name": 'Mary', "Age": 18, "HasWebSite": true, "Born": null , "_originalIndex": 2 }
]);
});
});
});
}
library sql_server_socket;
import "dart:io";
import "dart:async";
import "dart:convert";
import 'dart:typed_data';
import "table.dart";
class SqlConnection {
late Socket _socket;
late StringBuffer _receiveBuffer;
late Completer _completer;
late bool _connected;
late String _address;
late int _port;
late String _connectionString;
SqlConnection(String connStr,
{String address: "localhost", int port: 10980}) {
_address = address;
_port = port;
_connected = false;
_connectionString = connStr;
}
/// tells if database is connected
bool get connected => _connected;
/// connects to sql server database using the specified connection string
Future<bool> open() async {
try {
this._socket = await Socket.connect(_address, _port);
//print("Connected to: ${_socket.remoteAddress.address}:${_socket.remotePort}");
} catch (ex) {
// throw "can't connect to ${_address}:${_port} -- $ex";
throw "can't connect to $_address:$_port -- $ex";
}
//Establish the onData, and onDone callbacks
_socket
.transform(utf8.decoder as StreamTransformer<Uint8List, dynamic>)
.listen(_receiveData, onError: _onError, onDone: _onDone);
Completer<bool> connectCompleter = new Completer();
// String json = JSON.encode({"type": "open", "text": _connectionString});
String json = jsonEncode({"type": "open", "text": _connectionString});
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _OkResult) {
_connected = true;
connectCompleter.complete(true);
} else if (res is _ErrorResult) {
_connected = false;
connectCompleter.completeError(res.error);
} else
throw "unknown response";
}).catchError((err) {
_connected = false;
connectCompleter.completeError(err);
});
return connectCompleter.future;
}
/// disconnects from sql server
Future<bool> close() {
if (!connected) throw "not connected";
Completer<bool> disconnectCompleter = new Completer();
String json = jsonEncode({"type": "close", "text": ""});
_sendCommand(json).then((risp) {
var res = _parseResult(risp);
if (res is _OkResult) {
_connected = false;
disconnectCompleter.complete(true);
} else if (res is _ErrorResult) {
disconnectCompleter.completeError(res.error);
} else
throw "unknown response";
}).catchError((err) {
disconnectCompleter.completeError(err);
});
return Future.value(disconnectCompleter.future);
}
/// launch a query on the database, returning a table
Future<Table> queryTable(String sql) {
if (!connected) throw "not connected";
String json = jsonEncode({"type": "table", "text": sql});
Completer<Table> compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _TableResult) {
var tres = res;
Table tab = new Table(this, tres.tableName, tres.rows, tres.columns);
compl.complete(tab);
} else
throw "unknown response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
Future<PostBackResponse> postBack(ChangeSet chg) {
if (!connected) throw "not connected";
String params = jsonEncode(chg.toEncodable());
String json = jsonEncode({"type": "postback", "text": params});
Completer<PostBackResponse> compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _PostBackResult) {
var tres = res;
PostBackResponse resp = new PostBackResponse();
resp.idcolumn = tres.idcolumn;
resp.identities = tres.identities;
compl.complete(resp);
} else
throw "invalid postback response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
/// launch a query on the database, returning all rows
Future<List<Map<String, dynamic>>> query(String sql) {
if (!connected) throw "not connected";
String json = jsonEncode({"type": "query", "text": sql});
Completer<List<Map<String, dynamic>>> compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _QueryResult)
compl.complete(res.rows);
else
throw "unknown response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
/// launch a query on the database, returning the first rows only
Future<Map<String, dynamic>> querySingle(String sql) {
if (!connected) throw "not connected";
String json = jsonEncode({"type": "querysingle", "text": sql});
Completer<Map<String, dynamic>> compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _QueryResult) {
if (res.rows.length == 0)
compl.complete(null);
else
compl.complete(res.rows[0]);
} else
throw "unknown response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
/// launch a query on the database, returning the value from the first column of the first row
Future<dynamic> queryValue(String sql) {
if (!connected) throw "not connected";
String json = jsonEncode({"type": "queryvalue", "text": sql});
Completer compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _QueryResult) {
if (res.rows.length == 0)
compl.complete(null);
else
compl.complete(res.rows[0]["value"]);
} else
throw "unknown response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
/// executes a sql command, returning the number of rows affected
Future<int> execute(String sql) {
if (!connected) throw "not connected";
String json = jsonEncode({"type": "execute", "text": sql});
Completer<int> compl = new Completer();
_sendCommand(json).then((result) {
var res = _parseResult(result);
if (res is _ErrorResult)
compl.completeError(res.error);
else if (res is _QueryResult) {
if (res.rows.length == 0)
compl.complete(-1);
else
compl.complete(res.rows[0]["rowsAffected"]);
} else
throw "unknown response";
}).catchError((err) {
compl.completeError(err);
});
return compl.future;
}
/// formats and write a command to the socket
Future<String> _sendCommand(String command) {
// prepare buffer for response
_receiveBuffer = new StringBuffer();
Completer<String> _completer = new Completer();
String cmd = command.length.toString() + "\r\n" + command;
_socket.write(cmd);
return _completer.future;
}
void _onDone() {
//print("onDone()");
//socket.destroy();
}
void _onError(error) {
print("error occurred: $error");
}
/// receive data from socket and build a command string
///
/// client sends text-based commands with the format:
/// size_of_command_string + "\r\n" + command_string
void _receiveData(data) {
_receiveBuffer.write(data);
String content = _receiveBuffer.toString();
if (content.indexOf("\r\n") > 0) {
int x = content.indexOf("\r\n");
int len = int.parse(content.substring(0, x)); // size of command string
String cmd = content.substring(x + 2);
if (cmd.length == len) {
_completer.complete(cmd);
}
}
}
/// translates generic json result into a Result type
dynamic _parseResult(String json) {
Map result = jsonDecode(json);
if (result["type"] == "ok")
return new _OkResult("ok");
else if (result["type"] == "error")
return new _ErrorResult(result["error"]);
else if (result["type"] == "query")
return new _QueryResult(result["rows"], result["columns"]);
else if (result["type"] == "table")
return new _TableResult(
result["tablename"], result["rows"], result["columns"]);
else if (result["type"] == "postback")
return new _PostBackResult(result["idcolumn"], result["identities"]);
else
throw "unknown response";
}
}
class _ErrorResult {
late String error;
_ErrorResult(String error) {
this.error = error;
}
}
class _OkResult {
late String ok;
_OkResult(String ok) {
this.ok = ok;
}
}
class _QueryResult {
late List<Map<String, dynamic>> rows;
late Map<String, dynamic> columns;
_QueryResult(List<Map<String, dynamic>> rows, Map<String, dynamic> columns) {
this.rows = rows;
this.columns = columns;
// fix types
for (var fieldName in columns.keys) {
TypeFixer.fixColumn(rows, fieldName, columns[fieldName]);
}
}
}
class _TableResult {
late String tableName;
late List<Map<String, dynamic>> rows;
late List<Map<String, String>> columns;
_TableResult(String tableName, List<Map<String, dynamic>> rows,
List<Map<String, String>> columns) {
this.tableName = tableName;
this.rows = rows;
this.columns = columns;
}
}
class _PostBackResult {
late String idcolumn;
late List<int> identities;
_PostBackResult(String idcolumn, List<int> identities) {
this.idcolumn = idcolumn;
this.identities = identities;
}
}
/// translates a JSON encoded SQL type into a Dart type
class TypeFixer {
/// fix string data type coming from JSON into proper Dart data type
static void fixColumn(
List<Map<String, dynamic>> rows, String columnName, String columnType) {
if (columnType == "datetime") {
for (int t = 0; t < rows.length; t++) {
if (rows[t][columnName] != null)
rows[t][columnName] = DateTime.parse(rows[t][columnName]);
}
}
}
}
pubspec.yaml
name: sql_server_socket
version: 0.0.1
description: A minimal command-line application.
#author: <Antonino Porcino> <nino.porcino#gmail.com>
#homepage: https://github.com/nippur72/SqlServerSocket
environment:
sdk: ">=2.7.0 <3.0.0"
#dependencies:
# foo_bar: '>=1.0.0 <2.0.0'
dev_dependencies:
unittest: any
guinness: ">=1.3.0 <2.0.0"
I'm using Flutter Dart to develop an application, in that I'm trying to establish Sql connection with Sql server and application.
This is the link I referred for connection https://github.com/nippur72/SqlServerSocket .
While trying to add dependencies in pubspec.yaml, under dev_dependencies the version of guinness is not updating to the newer version(pub update). While clicking pub get i'm receiving this error,
Resolving dependencies...
Because sql_server_socket depends on guinness ^1.3.0 which doesn't match any versions, version solving failed.
Process finished with exit code 1
I have tried specifying the version manually and i know it doesn't work that way. So I used pub update, tried updating the whole flutter and dart version, yet receiving the same error.
Is there any other solution other than guinness? Or how can I get the actual guinness version. I have tried surfing thru internet for guinness versions but had no relevant result.
Please help me with this issue. I've been stuck with sql connection for past few days.
Thanks in advance!
Error message
You can use SQLite to store data locally and then use the package sql_conn 0.0.3 to do the insert/update operations on SQL Server.
I am going to try this suggestion myself this month, and will comment on my results.

Is there a way to insert object into DB using node.js mssql module

I found a few examples to insert objects into DB directly by doing something like:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'cccc.net',
user : 'username',
password : 'password',
});
var post = {srcUserID: userSrcID, destUserID: msg.userid, messageContent: msg.txt, messageSendDate:sendDate };
connection.query('INSERT INTO messages SET ?', post, function(err, result) {
});
But this works with mysql module and I have SQL Server as my DB so I am using
var SQL_DB = require('mssql');
Is there a way to insert objects directly to DB in the same way how its possible with mysql module.
looking at node-mssql v4 docs, they used this as an example using callbacks:
const sql = require('mssql');
const config = {
user: '...',
password: '...',
server: 'localhost',
database: '...',
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
}
};
const pool = new sql.ConnectionPool(config);
const transaction = new sql.Transaction(pool);
transaction.begin(err => {
// ... error checks
const request = new sql.Request(transaction)
request.query('insert into mytable (mycolumn) values (12345)', (err, result) => {
// ... error checks
transaction.commit(err => {
// ... error checks
console.log("Transaction committed.")
})
})
})
EDIT: node-mssql seems to use request.input for escaping values but does not accept a js object, you could quickly make your own:
sql.connect(config, err => {
var post = {
srcUserID: userSrcID,
destUserID: msg.userid,
messageContent: msg.txt,
messageSendDate: sendDate
};
const request = new sql.Request();
let cols = [];
let inputs = [];
for (let k in post) {
request.input(k, post[k]);
cols.push(k);
inputs.push('#' + k);
}
let query = `insert into messages (${cols.toString()}) values (${inputs.toString()})`;
request.query(query, (err, result) => {
//stuff here
});
});

Node Express Multiple SQL server Connection

I need to connect to diferent databases on direfent servers.
The servers are Microsoft SQL Server.
I do it like this:
dbconfig.js
var sql1 = require('mssql')
var sql2 = require('mssql')
var conn1 = {server:"SERVER IP", database:"db1", user:"foo", password:"foo", port:1433}
var conn2= {server:"SERVER2 IP", database:"db2", user:"foo2", password:"foo2", port:1433}
var server1= sql1.connect(conn1)
.then(function() { debug('Connected'); })
.catch(function(err) { debug('Error connect SQL Server', err); });
var server2= sql2.connect(conn2)
.then(function() { debug('Connected'); })
.catch(function(err) { debug('Error connect SQL Server', err); });
module.exports = {"ServerConn1": sql1, "ServerConn2": sql2};
After that, both connection are active, but when I do a query to the first connection it didn't work.
The error is Invalid object name 'FooDatabase.dbo.fooTable'.
Can anyone help me to solve this issue?
Thanks!
I implement using MySQL you can do the same thing mssql by passing empty database parameter and letter update database before creates connection.
And you do not need to import two-times just update the DB name before creating connection or query.
const express =
require('express');
const app = express();
const port = process.env.PORT || 80;
var http = require('http');
var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',//here i am not passing db and db is undefined
});
app.get('/db1',function(req,res)
{
connection.config.database="task" //here i updating db name before query
connection.query('SELECT * FROM tasks', function (error, results, fields) {
console.log(results)
res.json(fields)
connection.end()
})
})
app.get('/db2',function(req,res)
{
connection.config.database="cg_taskview" //db2
connection.query('SELECT * FROM tasks', function (error, results, fields) {
if (error)
console.log(error);
console.log(results)
res.json(fields)
});
connection.end()
})
var server = http.createServer(app);
server.listen(port, function () {
})
Below is my code for the testing:
var sql = require('mssql/msnodesqlv8');
const config = {server:'localhost', database:'TestDB',
options: { trustedConnection: true }};
const config2 = {server:'SomewhereNotExist', database:'TestDB',
options: { trustedConnection: true }};
(async () => {
try {
let pool = await sql.connect(config);
let result = await pool.request().query('select count(1) as cnt from AlarmWithLastStatus');
console.log('DB1 result:');
console.dir(result.recordset);
let pool2 = await sql.connect(config2);
let result2 = await pool2.request().query('select count(1) as cnt from AlarmWithLastStatus');
console.log('DB2 result:');
console.dir(result2.recordset);
} catch (err) {
if (err) console.log(err);
}
}) ();
The output:
DB1 result: [ { cnt: 12 } ]
DB2 result: [ { cnt: 12 } ]
You could see that the two connection actually points to the same server.
If you change the second query to a table that does not exist in this server, that will generate the error you got.
I started experiencing a similar problem when a second MSSQL server was added as a data source to the project ... Fortunately, I found a solution in the examples for tediousjs.
Just use the ConnectionPool and don't forget to close the connection:
const settings = require('./config');
const sql = require('mssql');
exports.someSqlQuery = async function(sqlQuery) {
const cPool = new sql.ConnectionPool(config);
cPool.on('error', err => console.log('---> SQL Error: ', err));
try {
await cPool.connect();
let result = await cPool.request().query(sqlQuery);
return {data: result};
} catch (err) {
return {error: err};
} finally {
cPool.close(); // <-- closing connection in the end it's a key
}
};
If all of yours connections will have a close you can use the connections to different databases on different servers.

How do I display all members in the member collection, using find in mongoose

I have an application built using the MEAN Stack, I am able to display one record at a time when using this method:
in my member model I have:
module.exports.getMemberByRFID = function(rfidkey, callback){
const query = {rfidkey: rfidkey}
Member.findOne(query, callback);
}
In my routes file I have:
// Authenticate Member
router.post('/authenticatemember', (req, res, next) => {
const rfidkey = req.body.rfidkey;
Member.getMemberByRFID(rfidkey, (err, member) => {
if(err) throw err;
if(member){
const token = jwt.sign(member, config.secret, {
expiresIn: 50 //1 week
});
res.json({
success: true,
token: 'JWT2 '+token,
member: {
id: member._id,
firstname: member.firstname,
surname: member.surname,
email: member.email,
expirydate: member.expirydate
}
});
} else {
return res.json({success: false, msg: 'member not found'});
}
})
});
In my AuthService.ts file I have:
authenticateMember(member){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/users/authenticatemember', member,{headers: headers})
.map(res => res.json());
}
And then in my angular TS file upfront I have:
onSearchSubmit(){
var inputElement = <HTMLInputElement>document.getElementById('rfidkey');
const member = {
rfidkey: inputElement.value
}
this.authService.authenticateMember(member).subscribe(data => {
if(data.success){
this.authService.storeMemberData(data.token, data.member)
console.log(data.member);
var newexpiry = new Date(data.member.expirydate);
var today = new Date();
if (today > newexpiry) {
this.flashMessage.show('member has expired', {
cssClass: 'alert-danger',
timeout: 5000});
} else {
this.flashMessage.show('member is active', {
cssClass: 'alert-success',
timeout: 5000});
}
var n = newexpiry.toString();
var inputElement = <HTMLInputElement>document.getElementById('firstname');
inputElement.value = data.member.firstname;
var inputElement = <HTMLInputElement>document.getElementById('surname');
inputElement.value = data.member.surname;
var inputElement = <HTMLInputElement>document.getElementById('email');
inputElement.value = data.member.email;
var inputElement = <HTMLInputElement>document.getElementById('expirydate');
inputElement.value = n;
// this.router.navigate(['searchmember']);
} else {
this.flashMessage.show(data.msg, {
cssClass: 'alert-danger',
timeout: 5000});
var inputElement = <HTMLInputElement>document.getElementById('firstname');
inputElement.value = "";
var inputElement = <HTMLInputElement>document.getElementById('surname');
inputElement.value = "";
var inputElement = <HTMLInputElement>document.getElementById('email');
inputElement.value = "";
var inputElement =
<HTMLInputElement>document.getElementById('expirydate');
inputElement.value = "";
this.router.navigate(['/searchmember']);
}
});
}
This gives me the following result:
Searching for a single record
Now what I want to do is have a page named Display All Members, and display all records in a datatable which can be searched and sorted.
Does anyone know how I can find ALL records with mongoose and send the list of all members to the front end Angular 2 application and place them in to the table?
thanks!

Resources