我是SQL Server的新手。当我使用MySQL时,使用'?'绑定变量非常容易。但是,我不知道如何在mssql
中绑定变量。
我试过了:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
var Myquery = "INSERT INTO person (idNumber, forename, surname, age, address, maritalStatus)" +
" VALUES( " + req.body.idNumber + ", " + req.body.forename + ", " + req.body.surname +
", " + req.body.age + ", " + req.body.address + ", " + req.body.maritalStatus + " )";
pool.request().query(Myquery, function (err, result) {
res.json(result);
})
我收到此错误:
无效的列名称'单一'。
然而,当我在SQL Server中直接执行我在这里创建的查询(Myquery)时,它顺利进行。我怎样才能解决这个问题?
编辑:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
const ps = new SQL.PreparedStatement(pool);
ps.input('param', SQL.NVarChar);
ps.prepare('SELECT * FROM @param', function (err) {
if (err) console.log('error: ' + err);
else {
ps.execute({param: 'person'}, function (err, result) {
console.log(result);
})
}
});
错误:ConnectionError:连接尚未打开。
我也用过这个:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
pool.request().input('param', SQL.NVarChar, 'person')
.query("SELECT * FROM @param", function (err, result) {
if (err) console.log('error: ' + err);
console.log(result);
});
错误:ConnectionError:连接已关闭。
答案 0 :(得分:0)
您的文字值需要单引号:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
var Myquery = "INSERT INTO person (idNumber, forename, surname, age, address, maritalStatus)" +
" VALUES( " + req.body.idNumber + ", '" + req.body.forename + "', '" + req.body.surname +
"', " + req.body.age + ", '" + req.body.address + "', '" + req.body.maritalStatus + "' )";
pool.request().query(Myquery, function (err, result) {
res.json(result);
})
这也是一个超级糟糕的主意,因为它允许SQL注入,因此可以通过这种方式创建基于输入的查询。你应该使用@parameters(https://blogs.msdn.microsoft.com/sqlphp/2008/09/30/how-and-why-to-use-parameterized-queries/)