[英]Using ODBC & Node.js to insert data
任何輸入將不勝感激。
我正在使用ODBC連接字符串通過node.js連接到我的sql數據庫。 我可以成功建立連接並查詢數據庫,但是在嘗試插入數據時遇到了麻煩。
可以在這里找到odbc插件: https : //www.npmjs.com/package/odbc
這是我嘗試重新創建的示例:
var db = require("odbc")()
, cn = "DRIVER={FreeTDS};SERVER=host;UID=user;PWD=password;DATABASE=dbname"
;
//Blocks until the connection is open
db.openSync(cn);
db.prepare("insert into hits (col1, col2) VALUES (?, ?)", function (err, stmt) {
if (err) {
//could not prepare for some reason
console.log(err);
return db.closeSync();
}
//Bind and Execute the statment asynchronously
stmt.execute(['something', 42], function (err, result) {
result.closeSync();
//Close the connection
db.closeSync();
});
})
這是我的代碼:
var db = require("odbc")()
, cn = "Driver={ODBC Driver 13 for SQL Server};Server=host:insert-name.database.windows.net,insert-port;Database=insert-database-name;Uid=insert-uid;Pwd=insert-password;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;"
;
//Blocks until the connection is open
//Blocks until the connection is open
db.openSync(cn);
//Blocks while preparing the statement
db.prepare("INSERT INTO Contact (FirstName, LastName, Country, User, Email, PrivacyAgreement, PhoneNumber) VALUES (?,?,?,?,?,?,?)", function (err, stmt) {
if (err) {
//could not prepare for some reason
console.log(err);
return db.closeSync();
}
console.log(stmt);
//Bind and Execute the statment asynchronously
stmt.execute(['first','last','country_name', 1, 'emailaccount@gmail.com', 1, '9999999999'], function (err, result) {
result.closeSync();
console.log(result);
//Close the connection
db.closeSync();
});
})
注意:“ User”和“ PrivacyAgreement”是位數據類型(布爾值),其余是varchar。
為此,我得到以下錯誤:
ODBCStatement { queue: SimpleQueue { fifo: [], executing: true } }
/path/to/file/insert.js:22
result.closeSync();
^
TypeError:無法讀取未定義的屬性“ closeSync”
由stmt.execute
返回的result
是不確定的,必須是因為拋出了err
,請檢查stmt.execute
的回調中是否有錯誤。
另外,您是否有特定的原因為什么要通過異步使用同步操作? 如果您在進行異步調用方面沒有任何限制,我建議您嘗試https://www.npmjs.com/package/tedious
感謝您的輸入; 我最終沒有切換到asyn(使用db.openSync建立連接和db.prepareSycn)。
該問題是由於使用“用戶”一詞引起的-“用戶”保留在我要連接的SQL數據庫中。 通過在語句字符串中的術語“用戶”中添加方括號,可以解決此問題。
以下代碼有效:
let stmt = db.prepareSync('插入聯系人(名字,姓氏,國家/地區,[用戶],電子郵件,PrivacyAgreement,電話號碼)VALUES(?,?,?,?,?,?,?)')
謝謝你們!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.