How to use the PreparedStatement function from mssql

Find comprehensive JavaScript mssql.PreparedStatement code examples handpicked from public code repositorys.

68
69
70
71
72
73
74
75
76
77
    '    SET NOCOUNT ON;' +
    '    SELECT name, email' +
    '    FROM UserTable' +
    '    WHERE name = @username;'
);
preparedStatementGlobal = new sql.PreparedStatement();
preparedStatementGlobal.input('username', sql.NVarChar(40));
preparedStatementGlobal.input('email', sql.NVarChar(40));
await preparedStatementGlobal.prepare('INSERT INTO UserTable (name, email) VALUES (@username, @email)');
ready = true;
fork icon34
star icon66
watch icon0

+ 11 other calls in file

22
23
24
25
26
27
28
29
30
31
var connection = new mssql.connect(config, function (err) {
  if (err) {
    console.log(err);
    return;
  }
  var ps = new mssql.PreparedStatement(connection);
  ps.prepare(sql, function (err) {
    if (err){
      console.log(err);
      return;
fork icon3
star icon14
watch icon0

26
27
28
29
30
31
32
33
34
35
if (noop) {
  return 'NOOP';
}

const pool = await initDb();
const ps = new sql.PreparedStatement(pool);

if (safe) {
  await ps.input('param', sql.NVarChar(sql.MAX));
  await ps.prepare('SELECT * FROM Students WHERE name = @param');
fork icon5
star icon9
watch icon0

100
101
102
103
104
105
106
107
108
109

SELECT SCOPE_IDENTITY() AS orderId;
`;

// Create prepared statement     
const psSummary = new sql.PreparedStatement(pool);
psSummary.input('OD', sql.DateTime);
psSummary.input('TA', sql.Decimal);
psSummary.input('SA', sql.VarChar);
psSummary.input('SCI', sql.VarChar);
fork icon0
star icon1
watch icon1

+ 39 other calls in file

200
201
202
203
204
205
206
207
208
209

_getPreparedArgs(args, outputField) {
  args = args || {};
  return this.getDB()
  .then((db) => {
    const request = new mssql.PreparedStatement(db);
    return this.validateAndProcess(args, 'toDB')
    .then((args) => {
      return Promise.resolve({ps: request, args});
    });
fork icon1
star icon0
watch icon2

+ 5 other calls in file

40
41
42
43
44
45
46
47
48
49

record = record.slice(0, record.length - 2);

(async () => {
        let conn = await db.connect()
        let ps = new sql.PreparedStatement(conn)
        try {
            //await ps.prepare("INSERT INTO LectureHistory (name, dateStr, timestamp) VALUES ('曹东江的自我修养','2019-04-05',0)")

            ps.input('cardnum', sql.VarChar(9))
fork icon0
star icon3
watch icon7

233
234
235
236
237
238
239
240
241
242
let ps
const input = {}
return connect
    .then(function(connection) {
      convertParams()
      ps = new mssql.PreparedStatement(connection)
      Object.keys(params).forEach(function(key) {
        const param = params[key]
        if (typeof param === 'object' && !(param instanceof Date)) {
          input[key] = param && param.value !== void 0 ? param.value : null
fork icon1
star icon0
watch icon0

195
196
197
198
199
200
201
202
203
204
const stmt =
  'INSERT INTO votes (time_cast, candidate) VALUES (@timestamp, @team)';
// Using a prepared statement protects against SQL injection attacks.
// When prepare is called, a single connection is acquired from the connection pool
// and all subsequent executions are executed exclusively on this connection.
const ps = new mssql.PreparedStatement(pool);
ps.input('timestamp', mssql.DateTime);
ps.input('team', mssql.VarChar(6));
await ps.prepare(stmt);
await ps.execute({
fork icon0
star icon1
watch icon0

703
704
705
706
707
708
709
710
711
712
 * runSP();
 */
async query(text, pObj, inputs, outputs) {
    let ret = createResult();
    if (this.connected) {
        let ps = new mssql.PreparedStatement(this.connection);
        
        let o = clone(pObj);
        prepare(ps, o, inputs, outputs);
        let isPrepared = false;
fork icon0
star icon0
watch icon0

+ 12 other calls in file

28
29
30
31
32
33
34
35
36
37
	`;			 

console.log(sqlStatement);

// Prepate and Execute the Statment
const ps = new sql.PreparedStatement(pool)
ps.prepare(sqlStatement, err => {
	// ... error checks
	ps.execute({
			}, (err, result) => {
fork icon0
star icon0
watch icon0

+ 4 other calls in file

11
12
13
14
15
16
17
18
19
20
21
});
const poolConnect = pool.connect();


let InsertFaculty = (pool, faculty, faculty_name, _cb) => {
    const cb = _cb?_cb:(err, result)=> {console.log('default cb')};
    let ps = new sql.PreparedStatement(pool);
    ps.input('faculty', sql.VarChar(10));
    ps.input('faculty_name', sql.VarChar(50));
    ps.prepare('INSERT INTO FACULTY (FACULTY, FACULTY_NAME ) VALUES (@faculty, @faculty_name)', err => {
        if (err) cb(err, null);
fork icon0
star icon0
watch icon0

+ 31 other calls in file

21
22
23
24
25
26
27
28
29
30
try {
    pool = await sql.connect(dbConfig);
    let customerIDQuery = `SELECT customerId
                           FROM customer
                           WHERE userid = @userid`;
    let preppedSql = new sql.PreparedStatement(pool);
    preppedSql.input('userid', sql.VarChar);
    await preppedSql.prepare(customerIDQuery);
    let customerResults = await preppedSql.execute({userid: userId});
    if (!customerResults.recordset[0]) {
fork icon0
star icon0
watch icon0

45
46
47
48
49
50
51
52
53
54
await preppedSql.prepare(getProductById);

let results = await preppedSql.execute({productId: productId});
let product = results.recordset[0];

let reviewPs = new sql.PreparedStatement(pool);
reviewPs.input('pid', sql.Int);
await reviewPs.prepare(reviewSql);

let reviewResults = await reviewPs.execute({pid: productId});
fork icon0
star icon0
watch icon0

44
45
46
47
48
49
50
51
52
let sqlQuery2 = `SELECT productId, quantity, price
                 FROM orderproduct
                 WHERE orderId = @ordId`;

// Executes sqlQuery2 and protects input from injection
let preparedStatement = new sql.PreparedStatement(pool);
preparedStatement.input('ordId', sql.Int);
await preparedStatement.prepare(sqlQuery2);
let results2 = await preparedStatement.execute({ordId: ordId});
fork icon0
star icon0
watch icon0

34
35
36
37
38
39
40
41
42
43
})
.then(async ()=>{
    let data;
    var json_execute2="{";
    const aux2= await new sql.ConnectionPool(objconn.conn).connect();
    const ps2=new sql.PreparedStatement(aux2);
    for(let i=0;i<campos_execute.length;i++){
        ps2.input(campos_execute[i],sql.VarChar);
        if(i<(campos_execute.length-1))json_execute2+='"'+campos_execute[i]+'":"'+valor_list2[i]+'",';
        else json_execute2+='"'+campos_execute[i]+'":"'+valor_list2[i]+'"';
fork icon0
star icon0
watch icon0

+ 13 other calls in file

5
6
7
8
9
10
11
12
13
14
var cadenasql = "SELECT " + campo + " FROM dbo." + tabla + " WHERE " + campo + "=@" + campo + ";";
var validacion;
try {
  var json_execute = '{"' + campo + '":' + '"' + dato + '"}';//string(que se pasara a json) para pool.execute
  const aux1 = await new sql.ConnectionPool(objconn.conn).connect();
  const ps1 = new sql.PreparedStatement(aux1);
  ps1.input(campo, sql.VarChar);
  json_execute = JSON.parse(json_execute);//de String a Json
  ps1.prepare(cadenasql).then(() => ps1.execute(json_execute)).then(_results => {
    if (_results.rowsAffected[0] > 0) { validacion = true }
fork icon0
star icon0
watch icon0

+ 2 other calls in file

3
4
5
6
7
8
9
10
11
12
13


/*
router.get('/query', async function(req, res, next) {
    let sql = require("mssql");

    const ps = new sql.PreparedStatement(req.app.locals.db);
    try {
        ps.input('brand_id', sql.Int);
        await ps.prepare("select * from production.products where brand_id = @brand_id")
        try {
fork icon0
star icon0
watch icon0

125
126
127
128
129
130
131
132
133
134
let cartQuery = `
    select incart.productId AS id, quantity, price, name, (price * quantity) AS subtotal
    from incart
    where userId = @username
`;
const preppedSql = new sql.PreparedStatement(pool);
preppedSql.input("username", sql.VarChar);
await preppedSql.prepare(cartQuery);
let results = await preppedSql.execute({username: username});
let dbCart = results.recordset;
fork icon0
star icon0
watch icon0

+ 4 other calls in file

80
81
82
83
84
85
86
87
88
89
                                                    customerId)
                          VALUES (@orderDate, @totalAmount, @address, @city, @state, @postalCode, @country,
                                  @customerId);
SELECT SCOPE_IDENTITY() AS orderId`;

preppedSql = new sql.PreparedStatement(pool);
preppedSql.input('orderDate', sql.DateTime);
preppedSql.input('totalAmount', sql.Decimal(10, 2));
preppedSql.input('address', sql.VarChar(50));
preppedSql.input('city', sql.VarChar(40));
fork icon0
star icon0
watch icon0

+ 2 other calls in file

11
12
13
14
15
16
17
18
19
20
  success: {
    description: 'Create manager with success'
  }
},
fn: async function getTablesProperties({connection}, {success}) {
  const psGetType = new mssql.PreparedStatement(connection);
  const preparedStatement = await psGetType.prepare(`
    SELECT DATA_TYPE,
           TABLE_NAME,
           COLUMN_NAME,
fork icon0
star icon0
watch icon1