3 node操作数据库

传统和orm型的方式操作数据库的区别

  •  传统的方式

        mysql2库 用来连接mysql和编写sql语句编写不方便也会有sql注入的风险

  •  orm的方式

Knex是一个基于JavaScript的查询生成器,它允许你使用JavaScript代码来生成和执行SQL查询语句。它提供了一种简单和直观的方式来与关系型数据库进行交互,而无需直接编写SQL语句。你可以使用Knex定义表结构、执行查询、插入、更新和删除数据等操作。

knexjs.org/guide/query…

 Prisma 是一个现代化的数据库工具套件支持ts很友好,用于简化和改进应用程序与数据库之间的交互。它提供了一个类型安全的查询构建器和一个强大的 ORM(对象关系映射)层,使开发人员能够以声明性的方式操作数据库。
Prisma 支持多种主流数据库,包括 PostgreSQL、MySQL 和 SQLite,它通过生成标准的数据库模型来与这些数据库进行交互。使用 Prisma,开发人员可以定义数据库模型并生成类型安全的查询构建器,这些构建器提供了套直观的方法来创建、更新、删除和查询数据库中的数据。
Prisma 的主要特点包括:

类型安全的查询构建器:Prisma 使用强类型语言(如 TypeScript)生成查询构建器,从而提供了在编译时捕获错误和类型检查的能力。这有助于减少错误,并提供更好的开发人员体验。
强大的 ORM 层:Prisma 提供了一个功能强大的 ORM 层,使开发人员能够以面向对象的方式操作数据库。它自动生成了数据库模型的 CRUD(创建、读取、更新、删除)方法,简化了与数据库的交互。
数据库迁移:Prisma 提供了数据库迁移工具,可帮助开发人员管理数据库模式的变更。它可以自动创建和应用迁移脚本,使数据库的演进过程更加简单和可控。
性能优化:Prisma 使用先进的查询引擎和数据加载技术,以提高数据库访问的性能。它支持高级查询功能,如关联查询和聚合查询,并自动优化查询以提供最佳的性能

1 mysql2操作数据库

下载依赖

npm install mysql2 express js-yaml

  1. mysql2 用来连接mysql和编写sq语句
  2. express 用来提供接口 增删改差
  3. js-yaml 用来编写配置文件

数据库配置 vscode数据库可视化插件可使用Database client,本地需安装mysql

代码:

db.config.yaml:

db:
   host: localhost #主机
   port: 3306 #端口
   user: root #账号
   password: '123456' #密码 一定要字符串
   database: test # 库

app.js:

import mysql2 from 'mysql2/promise'
import fs from 'node:fs'
import jsyaml from 'js-yaml'
import express from 'express'
const yaml = fs.readFileSync('./db.config.yaml', 'utf8')
const config = jsyaml.load(yaml)
const sql = await mysql2.createConnection({ //连接数据库
   ...config.db
})
const app = express()
app.use(express.json())
//查询接口 全部
app.get('/',async (req,res)=>{
   const [data] = await sql.query('select * from user')
   res.send(data)
})
//单个查询 params
app.get('/user/:id',async (req,res)=>{
    const [row] = await sql.query(`select * from user where id = ?`,[req.params.id])
    res.send(row)
})

//新增接口
app.post('/create',async (req,res)=>{
    const {name,age,hobby} = req.body
    await sql.query(`insert into user(name,age,hobby) values(?,?,?)`,[name,age,hobby])
    res.send({ok:1})
})

//编辑
app.post('/update',async (req,res)=>{
    const {name,age,hobby,id} = req.body
    await sql.query(`update user set name = ?,age = ?,hobby = ? where id = ?`,[name,age,hobby,id])
    res.send({ok:1})
})
//删除
app.post('/delete',async (req,res)=>{
    await sql.query(`delete from user where id = ?`,[req.body.id])
    res.send({ok:1})
})
const port = 3000

app.listen(port, () => {
   console.log(`Example app listening on port ${port}`)
})

2 orm框架knex操作数据库

下载依赖

npm install knex express js-yaml

db.config.yaml 同上配置 

app.js

import fs from 'node:fs'
import jsyaml from 'js-yaml'
import express from 'express'
import knex from 'knex'
const yaml = fs.readFileSync('./db.config.yaml', 'utf8')
const config = jsyaml.load(yaml) //类似转义或解码的操作
const db = knex({
  client: "mysql2",
  connection: config.db
})

//创建表 
/* db.schema.createTableIfNotExists('list', (table) => { 
  table.increments('id') //id自增
  table.integer('age') //age 整数
  table.string('name') //name 字符串
  table.string('hobby') //hobby 字符串
  table.timestamps(true, true) //创建时间和更新时间
}).then(() => {
  console.log('创建成功')
}) */

const app = express()
app.use(express.json())
//查询接口 全部
app.get('/', async (req, res) => {
  const data = await db('list').select().orderBy('id', 'desc')
  const total = await db('list').count('* as total')
  res.json({
    code: 200,
    data,
    total: total[0].total,
  })
})
//单个查询 params
app.get('/user/:id', async (req, res) => {
  const row = await db('list').select().where({ id: req.params.id })
  res.json({
    code: 200,
    data: row
  })
})

//新增接口
app.post('/create', async (req, res) => {
  const { name, age, hobby } = req.body
  const detail = await db('list').insert({ name, age, hobby })
  res.send({
    code: 200,
    data: detail
  })
})

//编辑
app.post('/update', async (req, res) => {
  const { name, age, hobby, id } = req.body
  const info = await db('list').update({ name, age, hobby }).where({ id })
  res.json({
    code: 200,
    data: info
  })
})
//删除
app.post('/delete', async (req, res) => {
  const info = await db('list').delete().where({ id: req.body.id })
  res.json({
    code: 200,
    data: info
  })
})
const port = 3000

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

index.http 方便测试接口

# 添加数据
POST http://localhost:3000/create HTTP/1.1
Content-Type: application/json

{
    "name":"张三",
    "age":18
}

# 查询全部
#  GET http://localhost:3000/ HTTP/1.1

# 单个查询
# GET http://localhost:3000/user/2 HTTP/1.1



# 更新数据
# POST http://localhost:3000/update HTTP/1.1
# Content-Type: application/json

# {
#     "name":"法外狂徒",
#     "age":20,
#     "id":23
# }


#删除
# POST http://localhost:3000/delete HTTP/1.1
# Content-Type: application/json

# {
#     "id":24
# }

3 事务

你可以使用事务来确保一组数据库操作的原子性,即要么全部成功提交,要么全部回滚

例如A给B转钱,需要两条语句,如果A语句成功了,B语句因为一些场景失败了,那这钱就丢了,所以事务就是为了解决这个问题,要么都成功,要么都回滚,保证金钱不会丢失。

//伪代码
db.transaction(async (trx) => {
    try {
        await trx('list').update({money: -100}).where({ id: 1 }) //A
        await trx('list').update({money: +100}).where({ id: 2 }) //B
        await trx.commit() //提交事务
    }
    catch (err) {
        await trx.rollback() //回滚事务
    }
   
})

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值