我正在使用TypeScript和mssql(v4)NodeJS程序包将我的应用程序连接到SQL Server数据库。
我正面临着似乎没有调用为sql.ConnectionPool定义的代码,而且我无法弄清原因。
基本上,我想使用准备好的语句执行INSERT操作。
这是我的CRUD.ts文件的代码:
var sql = require('mssql');
var config = {
server: 'localhost',
database: 'MyDB',
user: 'MyUser',
password: '*******',
port: '1433'
};
export async function newItem(someValue1: string, someValue2: string) {
try {
const db = new sql.ConnectionPool(config, err => {
console.info("Checking for errors...");
if (err) {
console.error("Connection failed: " + err);
} else {
console.info("Connected")
const insertStatement = 'INSERT INTO [dbo].[MyData]([SomeValue1],[SomeValue2])VALUES(@SomeValue1, @SomeValue2)';
const ps = new sql.PreparedStatement(db);
ps.input('SomeValue1', sql.String)
ps.input('SomeValue2', sql.String)
ps.prepare(insertStatement, err => {
if (err) {
console.error(err);
} else {
ps.execute({
SomeValue1: someValue1,
SomeValue2: someValue2
}, (err, result) => {
if (err) {
console.error(err);
} else {
ps.unprepare(err => {
if (err) {
console.error(err);
}
});
}
});
}
});
}
});
}catch (e) {
console.error(e);
}
}
我尝试按照mssql文档中的几个示例进行操作,但均未成功。
任何形式的帮助将非常感激。
提前致谢。
最佳答案
我从未使用过这个特定的库,但我认为重写您的代码以使用async/await
会很有帮助,尤其是因为您已经将该函数本身标记为异步。如果这样做,则对await newItem(...)
的调用将等待所有处理完成,而不是像现在这样立即返回,而不会立即触发任何回调。
我认为这是您的代码的样子(但未经测试,因此可能会有一些错误):
var sql = require('mssql');
var config = {
server: 'localhost',
database: 'MyDB',
user: 'MyUser',
password: '*******',
port: '1433'
};
export async function newItem(someValue1: string, someValue2: string) {
let db;
try {
db = await new sql.ConnectionPool(config).connect();
}
catch(err) {
console.error("Connection failed: " + err);
throw(err);
}
try {
console.info("Connected")
const insertStatement = 'INSERT INTO [dbo].[MyData]([SomeValue1],[SomeValue2])VALUES(@SomeValue1, @SomeValue2)';
const ps = new sql.PreparedStatement(db);
ps.input('SomeValue1', sql.String)
ps.input('SomeValue2', sql.String)
await ps.prepare(insertStatement);
await ps.execute({
SomeValue1: someValue1,
SomeValue2: someValue2
});
await ps.unprepare();
} catch (e) {
console.error(e);
throw(e);
}
}
请注意,由于文档似乎暗示需要这样做,因此我在池上添加了对
.connect()
的调用。当您使用await
时,任何错误都应作为Promise
拒绝返回,而await
会变成异常。这意味着无需检查每个调用是否有错误代码,您只需要一个try...catch
(实际上,这里有两个可以保留用于连接错误的不同消息)。我还重新抛出了错误,以告知调用者代码失败。如果您只是想让错误泛滥到调用者,那么您也可以完全删除错误处理:由于错误变成了Promise拒绝或异常,它们将向上传播。