node sequelize 4.13 模块 建立 mysql 数据连接

日期: 2017-10-20         浏览量: 2889

安装   


// Using NPM 


$ npm install--save sequelize 



# And one of the following: 


$ npm install--save pg pg-hstore 
$ npm install--save mysql2
$ npm install--save sqlite3 
$ npm install--save tedious // MSSQL 



// Using Yarn 


$ yarn add sequelize 



# And one of the following: 


$ yarn add pg pg-hstore 
$ yarn add mysql2 
$ yarn add sqlites 
$ yarn add tedious// MSSQL


建立连接


Sequelize将在初始化时设置连接池,因此如果从单个进程连接到DB,则最好只能在每个数据库中创建一个实例。如果要从多个进程连接到数据库,则必须为每个进程创建一个实例,但每个实例应具有最大连接池大小“max连接池大小除以实例数”。因此,如果您希望最大连接池大小为90,并且有3个工作进程,则每个进程的实例应具有30的最大连接池大小。



constsequelize=newSequelize('database','username','password', { 
    host:'localhost', 
    dialect:'mysql'|'sqlite'|'postgres'|'mssql', 
    pool:{max:5,min:0,idle:10000}, 
    // SQLite only 
    storage:'path/to/database.sqlite' 
}); 
        
// Or you can simply use a connection uri 
constsequelize=newSequelize('postgres://user:pass@example.com:5432/dbname');




测试连接


您可以使用这样的.authenticate()功能来测试连接。



sequelize 
    .authenticate()
    .then(()=>{ 
        console.log('Connection has been established successfully.'); 
    }) 
    .catch(err=>{ 
        console.error('Unable to connect to the database:',err); 
    });