Sequelizeとは
SequelizeとはNode.js用のORマッパーである。
SQLは自動生成されるので、モデル用のオブジェクトを定義すれば、メソッド操作によりデータベースのCRUD操作が行える。
モデル用のオブジェクトを使用する場合はSQLを指定することができないが、直接SQLを指定して実行する機能もある。
- 公式サイト:https://sequelize.org/
インストール
インストールはNPMとして提供されているため、次のコマンドで環境にインストールできる。
npm install sequelize
サンプル
Raw queries
直接SQLを指定して実行する場合。データベースはMySQLを使用する。
参考:https://sequelize.org/master/manual/raw-queries.html
- 参照
※SQLの変数は名前を指定せずに “?” でも渡せる。その場合、配列で値を渡す。const Sequelize = require('sequelize'); const connection = new Sequelize( 'dbname', 'username', 'password', { dialect:'mysql', host:'host', } ); connection.query('select * from test where id=:id',{ raw:true, replacements:{ id:45 } }).then(function(dbresult) { // 処理を行う // dbresultの結果は同じものが2件入っているので、dbresult[0]のみ使用する。 }).catch(function(dberror){ // エラー処理を行う // dberror.originalにデータベースが返したエラーが格納されている });
- エラーオブジェクト
{ "name": "SequelizeDatabaseError", "parent": { "code": "ER_TABLEACCESS_DENIED_ERROR", "errno": 1142, "sqlState": "42000", "sqlMessage": "SELECT command denied to user 'userXXX' for table 'testg'", "sql": "select * from testg where id=45" }, "original": { "code": "ER_TABLEACCESS_DENIED_ERROR", "errno": 1142, "sqlState": "42000", "sqlMessage": "SELECT command denied to user 'userXXX' for table 'testg'", "sql": "select * from testg where id=45" }, "sql": "select * from testg where id=45" }
- insert処理
connection.query('insert into test (val1,val2) values (:val1,:val2)',{ raw:true, replacements:{ val1:2, val2:3, } }).then(function(dbresult) { const InsertId = dbresult[0]; const RowCount = dbresult[1]; // 処理を行う }).catch(function(dberror){ // エラー処理を行う // dberror.originalにデータベースが返したエラーが格納されている });
- await版
呼び出し元関数はasyncにすること
try { let dbresult = await connection.query('select * from test where id=:id',{ raw:true, replacements:{ id:45 }); // 処理を行う } catch(dberror) { // 処理を行う }