Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

sql server - nodejs mssql insert with parameters

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;
            })
        })
    }
) 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...