node连接mysql的几种方法_浅谈node连接mysql数据库的方法

node使用原生方式,连接mysql数据库

a589fe02c65b9d84fb72622f9530495a.png

(async () => {

// 链接数据库

const mysql = require('mysql2/promise'); // npm i mysql2

const cfg = {

host: 'localhost',

user: 'root',

password: ';he%0f_,ljyW',

database: 'izengx',

}

const connection = await mysql.createConnection(cfg);

// 创建一个新表tests

let ret = await connection.execute(`CREATE TABLE IF NOT EXISTS tests (

id INT NOT NULL AUTO_INCREMENT,

message VARCHAR(45) NULL,

PRIMARY KEY (id)

)`)

console.log('create', ret);

// 新建数据

ret = await connection.execute(`INSERT INTO tests(message) VALUE(?)`, ['newData'])

console.log('新建数据', ret);

const [rows, fields] = await connection.execute(`

SELECT * FROM tests

`)

console.log('查询数据', rows);

})()

使用数据库中间件(ORM):sequelize连接和操作数据库

861a3845190830df38e0620384b3bdce.png

(async () => {

// 使用数据库中间件(ORM):sequelize连接和操作数据库

// 1. 使用Sequelize时,生成的表名会自动加成复数s,如fruit->fruits

// 2. 自动生成主键id,自增(缺点是合并新旧数据时,id又从1开始,会有重合)

const Sequelize = require('sequelize');

const sequelize = new Sequelize('izengx', 'root', ';he%0f_,ljyW', {

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}

})

// 同步数据库

let ret = await Fruit.sync();

// 增加一条数据

ret = await Fruit.create({

name: 'apple',

price: 3.5

})

// 更新数据

await Fruit.update({

price: 4,

}, {

where: {

name: 'banana',

}

})

// 查询

ret = await Fruit.findAll();

// 查询指定范围的数据

const Op = Sequelize.Op;

opRet = await Fruit.findAll({

where: {

price: {

[Op.gt]: 3,

[Op.lt]: 5,

}

}

})

console.log('search: '+ JSON.stringify(opRet));

})()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值