最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會(huì)員登陸 & 注冊(cè)

node.js使用Sequelize操作數(shù)據(jù)庫(kù)

2022-05-24 09:16 作者:地理信息技術(shù)雜談  | 我要投稿

Sequelize是一個(gè)基于 promise 的 Node.js ORM(對(duì)象關(guān)系映射)。

目前支持 Postgres、MySQL、MariaDB、SQLite和Microsoft SQL Server;?它具有強(qiáng)大的事務(wù)支持, 關(guān)聯(lián)關(guān)系, 預(yù)讀和延遲加載,讀取復(fù)制等功能。

官方網(wǎng)址:

https://sequelize.org/v5/index.html

npm安裝:npm install --save sequelize

使用何種數(shù)據(jù)庫(kù),要安裝對(duì)應(yīng)的npm類庫(kù),對(duì)應(yīng)的幾類數(shù)據(jù)庫(kù)安裝:


數(shù)據(jù)庫(kù)的初始化代碼:

const Sequelize = require('sequelize');

//第一種方式:傳遞數(shù)據(jù)庫(kù)連接信息(ip、端口、用戶名密碼等)

sequelize = new Sequelize('database', 'username', 'password',{host: 'localhost',?dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */});

//第二種方式:使用uri的字符串連接方式

sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');

驗(yàn)證數(shù)據(jù)庫(kù)連接是否成功:

sequelize.authenticate().then(() => {?? ? ?console.log('Connection has been established successfully.');

}).catch(err => {console.error('Unable to connect to the database:', err);});

// await方式:

???await?sequelize.authenticate();

數(shù)據(jù)庫(kù)的操作上,只要是以模型和數(shù)據(jù)庫(kù)的表進(jìn)行對(duì)應(yīng),同時(shí)也支持sql語句的查詢方式。

模型定義(https://sequelize.org/v5/manual/models-definition.html):

const Model = Sequelize.Model;

class User extends Model {}

User.init({

//屬性設(shè)置 ??

? firstName: { ?type: Sequelize.STRING, ?allowNull: false ? }, ? ??

?lastName: { ? ? ? type: Sequelize.STRING ? ??}}, {?

//屬性設(shè)置 ?

? sequelize, ? modelName: 'user' ??});

需要注意的是,上述定義一個(gè)user的模型,需要對(duì)應(yīng)在數(shù)據(jù)庫(kù)表中,有users這個(gè)表,要實(shí)現(xiàn)自己定義表名,需要在屬性中設(shè)置以下兩個(gè)參數(shù):

freezeTableName:?false,

tableName:?'define_user'

直接執(zhí)行sql語句查詢(https://sequelize.org/v5/manual/raw-queries.html):

sequelize.query("SELECT * FROM `users`", { type: sequelize.QueryTypes.SELECT}) ?.then(users => { ? ?//返回json對(duì)象 ?})

參考文檔:
官網(wǎng):

https://sequelize.org/v5/index.html

中文文檔網(wǎng)站:

https://github.com/demopark/sequelize-docs-Zh-CN

node.js使用Sequelize操作數(shù)據(jù)庫(kù)的評(píng)論 (共 條)

分享到微博請(qǐng)遵守國(guó)家法律
长子县| 崇信县| 江源县| 西昌市| 镇宁| 柳河县| 聂拉木县| 塘沽区| 安丘市| 双鸭山市| 密山市| 兰西县| 石楼县| 吴桥县| 宝鸡市| 安化县| 澄江县| 徐闻县| 余干县| 兴和县| 迭部县| 潼关县| 洪江市| 漠河县| 于田县| 甘孜县| 新乡市| 新乐市| 武隆县| 改则县| 西乌珠穆沁旗| 崇州市| 喀喇| 武邑县| 达州市| 浮山县| 彭泽县| 石阡县| 贡觉县| 民乐县| 万州区|