【ノード】Mysql 2とsequelize

9834 ワード

mysql2
npm i--save mysql 2のインストール
接続var mysql=require(‘mysql’);//1.接続構成の作成
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});

//2.データベースへの接続(このステップを省略して、データベースを直接クエリーして暗黙的にリンクすることができます)
connection.connect();

//3.データベースの問合せ
connection.query('SELECT 1 + 1 AS solution',(error, results, fields)=>{
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});

//4.データベース接続の切断
connection.end();

接続構成
よく使用されるhost接続するデータベースのホスト名.(デフォルト:localhost)protポート番号に接続するには、デフォルト3306 localAddress TCP接続のソースIPアドレスuser MySQLデータベース接続ユーザ名password MySQLデータベース接続パスワードdatabase接続のデータベース名(オプション)connectTime Out接続MySQLタイムアウトdataStrings強制日付タイプ(TIMESTAMP,DATETIME,DATE)を文字列として返します.JavaScript Dateオブジェクトに膨張するのではありません.true/falseが文字列として保持するタイプ名配列であってもよい.(デフォルト:false)multipleStatementsクエリーごとに複数のmysql文を許可します.この点に注意すると、SQL注入攻撃の範囲が増える可能性があります.(デフォルト:false)
url形式でデータベース接続構成の設定var connection=mysqlを行うことができる.createConnection(‘mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700’);
接続の終了
//1.endメソッドで閉じることでコールバック関数を渡すことができます
connection.end( (err) => {
    if(err) {
        console.log(err) 
    }else {
        console.log('       ')
    }
})

//2.destoryメソッドで閉じると、コールバック関数を渡すことはできません
connection.destory()

endは、キュー状態のクエリーキューが実行され、戻って接続が終了することを確認します.destory即時終了
検索
使用するquery(sqlString,values,callback)関数のクエリの最初のパラメータは、クエリ文字列です.たとえば、「SELECT*FROM books WHERE author=?」
2番目のパラメータは、クエリー文字列パラメータの値です.これは配列です.たとえば、['David']
‘SELECT * FROM books WHERE author = ?’ で、ヒントを有効にします.の値
3番目のパラメータは、クエリーの終了後のコールバック関数です.たとえば、次のようなクエリー・データが含まれます.
function (error, results, fields) {
  // error will be an Error if one occurred during the query
  // results will contain the results of the query
  // fields will contain information about the returned results fields (if any)
});

完全なquery関数:
connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {
  // error will be an Error if one occurred during the query
  // results will contain the results of the query
  // fields will contain information about the returned results fields (if any)
});

Sequelize
https://demopark.github.io/sequelize-docs-Zh-CN/PromiseベースのORM(Object Relation Mapping)は、複数のデータベース、トランザクション、関連付けなどをサポートします.
インストールnpm install--save sequelize
対応するデータベースドライバのインストールnpm install--save mysql 2
接続の確立
(async () => {
const Sequelize = require("sequelize");
//     
const sequelize = new Sequelize("kaikeba", "root", "example", {
    host: "localhost",
    dialect: "mysql", //       
    operatorsAliases: false
});
//     
const Fruit = sequelize.define("Fruit", {
    name: { type: Sequelize.STRING(20), allowNull: false },
    price: { type: Sequelize.FLOAT, allowNull: false },
    stock: { type: Sequelize.INTEGER, defaultValue: 0 }
});
//      ,force: true         Fruit.sync({force: true})
let ret = await Fruit.sync()
console.log('sync',ret)
ret = await Fruit.create({
    name: "  ",
    price: 3.5
})
console.log('create',ret)
ret = await Fruit.findAll()
await Fruit.update(
    { price: 4 },
    { where: { name:'  '} }
)
console.log('findAll',JSON.stringify(ret))
const Op = Sequelize.Op;
ret = await Fruit.findAll({
    // where: { price: { [Op.lt]:4 }, stock: { [Op.gte]: 100 } }
    where: { price: { [Op.lt]: 4, [Op.gt]: 2 } }
})
    console.log('findAll', JSON.stringify(ret, '', '\t'))
})()

タイムスタンプフィールドの自動生成を回避するモデルのデフォルトにid(プライマリ・キー、自己増加)、createdAt(作成時間)、updatedAt(更新時間)が含まれている場合、timestamps:falseを追加します.
const Fruit = sequelize.define("Fruit", {}, {
    timestamps: false
});

モデルを生成する2つの方法1、defineを用いて生成する、本質的には内部でModelを呼び出す.init
const Fruit = sequelize.define("Fruit", {
    name: { type: Sequelize.STRING(20), allowNull: false },
    price: { type: Sequelize.FLOAT, allowNull: false },
    stock: { type: Sequelize.INTEGER, defaultValue: 0 }
});

2、Model生成を使用し、そのinitメソッド生成モデルを実現する必要がある
const Model = sequlize.Model
class Fruit extends Model {
    Fruit.init({
        firstName:{
                type:Sequelize.STRING
        }
    },{
        sequlize,  //      
        modelName:'Fruit'  //      
    })
}

操作データベースはFruitを通過する.sync()メソッドで操作し、メソッドはPromiseを返します.
  //      ,force: true        
    sequelize.sync({ force: true }).then(async () => {
        await Team.create({ name: '  ' });
        await Player.bulkCreate([{ name: '  ', teamId: 1 }, { name: '  ', teamId: 1 }]);

        // 1       
        const players = await Player.findAll({ include: [Team] });
        console.log(JSON.stringify(players, null, 2));

        // N     
        const team = await Team.findOne({ where: { name: '  ' }, include: [Player] });
        console.log(JSON.stringify(team, null, 2));
    });

検索
追加create削除destory変更update検索find
//すべてのユーザーの検索
User.findAll().then(users => {
  console.log("All users:", JSON.stringify(users, null, 4));
});

//新規ユーザーの作成
User.create({ firstName: "Jane", lastName: "Doe" }).then(jane => {
  console.log("Jane's auto-generated ID:", jane.id);
});

//「ジェーン」という名前の人を全て削除
User.destroy({
  where: {
    firstName: "Jane"
  }
}).then(() => {
  console.log("Done");
});

//姓のない人をすべて「Doe」に変える
User.update({ lastName: "Doe" }, {
  where: {
    lastName: null
  }
}).then(() => {
  console.log("Done");
});

モデルのプロパティの定義
class Foo extends Model {}
Foo.init({
 //      ,        TRUE
     flag: { 
         type: Sequelize.BOOLEAN,   //    
         allowNull: false,  //     false     true      
         defaultValue: true,  //   
         unique: 'compositeIndex',  //   
         primaryKey: true, //    
        autoIncrement: true , //    
        validate: {  //      
            is: ["^[a-z]+$",'i'],     //      
            is: /^[a-z]+$/i,          //         ,           
            ……
        }
     }
})

Getters&settersはgetterとsetterを定義し、属性上でもモデル上でも定義できます.属性定義の優先度がモデル定義より高い
注意:setDataValue()とgetDataValue()関数(下位レベルの「データ値」プロパティに直接アクセスするのではなく)を使用することが重要です.これにより、カスタムgetterとsetterを下位モデルから保護できます.
class Employee extends Model {}
Employee.init({
    //      
  get fullName() {
    return this.firstname + ' ' + this.lastname;
  }

  set fullName(value) {
    const names = value.split(' ');
    this.setDataValue('firstname', names.slice(0, -1).join(' '));
    this.setDataValue('lastname', names.slice(-1).join(' '));
  }
  name: {
    type: Sequelize.STRING,
    allowNull: false,
    //      
    get() {
      const title = this.getDataValue('title');
      // 'this'           
      return this.getDataValue('name') + ' (' + title + ')';
    },
  },
  title: {
    type: Sequelize.STRING,
    allowNull: false,
    //      
    set(val) {
      this.setDataValue('title', val.toUpperCase());
    }
  }
}, { sequelize, modelName: 'employee' });

Employee
  .create({ name: 'John Doe', title: 'senior engineer' })
  .then(employee => {
    console.log(employee.get('name')); // John Doe (SENIOR ENGINEER)
    console.log(employee.get('title')); // SENIOR ENGINEER
  })

テーブルの削除//テーブルの作成:Project.sync()
//強制作成!Project.sync({force:true})/テーブルを破棄して再作成します
//削除表:Project.drop()
検索find特定要素の検索
//      ids,     123 
Project.findByPk(123).then(project => {
  // project    Project     ,         id 123      .
  //            ,    null
})

//     
Project.findOne({ where: {title: 'aProject'} }).then(project => {
  // project    Projects    title   'aProject'         || null
})

findOrCreateは要素を検索し、なければ検索したデータを作成するか、関数createdを作成します.
User
  .findOrCreate({where: 
  {username: 'sdepold'}, 
  defaults: {job: 'Technical Lead JavaScript'}
  }).then(([user, created]) => {
    console.log(user.get({
      plain: true
    }))
    console.log(created)
  }

findAndCountはデータベースで複数の要素を検索し、戻りデータと総カウント戻り値には2つの属性があります.rowsは配列であり、検索された要素countは整数であり、検索された要素の総数を返します.
Project
  .findAndCountAll({
     where: {
        title: {
          [Op.like]: 'foo%'
        }
     },
     offset: 10,
     limit: 2
  })
  .then(result => {
    console.log(result.count);
    console.log(result.rows);
  });

findAllは、条件を満たすすべての要素を返します.
Project.findAll({group: 'name'})

maxは最大値を返します
Project.max('age').then(max => {
  //     40
})

minは最小値を返す
Project.min('age').then(max => {
  //     40
})

count統計エントリ数
Project.count().then(c => {
  console.log("There are " + c + " projects!")
})

sum統計特定属性値の和
Project.sum('age').then(sum => {
  //     55
})