2017-11-17 6 views
0

任意の入力をいただければ幸いです。ODBC&Node.jsを使用してデータを挿入する

私は、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, '[email protected]', 1, '9999999999'], function (err, result) { 
    result.closeSync(); 
    console.log(result); 

    //Close the connection 
    db.closeSync(); 
    }); 
}) 

注: ' User 'と' PrivacyAgreement 'はビットデータ型(ブール値)で、残りはvarcharです。

れ、私は次のエラーを取得するには、次のstmt.executeによって返さ未定義

答えて

1

resultの 'closesyncのが' 未定義であるプロパティを読み取ることができませんerrがスローされているためでなければならない、のチェック:

ODBCStatement { queue: SimpleQueue { fifo: [], executing: true } } 
/path/to/file/insert.js:22 

result.closeSync(); 

    ^

はTypeErrorをstmt.executeのコールバックでエラーが発生しました。

また、asynで同期操作を使用する特別な理由はありますか? 非同期呼び出しに制約がない場合は、試してみることをおすすめします。https://www.npmjs.com/package/tedious

0

ありがとうございます。私は最終的にasyn(db.openSyncを使用して接続とdb.prepareSycnを確立する)に切り替えました。

問題は、「ユーザー」という用語を使用することによって発生しました。「ユーザー」は、接続先のSQLデータベースに予約されています。この問題は、ステートメント文字列の中の用語「User」に角括弧を追加することで解決しました。

次のコードは動作します:

レットのstmt = db.prepareSyncは( '連絡先(姓、姓、国に挿入、[ユーザー]、電子メール、PrivacyAgreement、PhoneNumberの)VALUES(、、、???? 、?、?、?) ')

ありがとうございました!

関連する問題