可持续化存储

目录

mysql

Sequelize 

mongodb

mongoose


mysql

 四个步骤:

  1. 安装:npm i mysql -S 
  2. 导入:const mysql = require('mysql') 
  3. 创建:const conn = mysql.createConection({host:xxx,user:xxx,password:xxx,database:xxx})
  4. 连接:conn.connect()

具体表操作看下面的例子:

// 1.安装 npm i mysql -S 
// 2.导入模块
const mysql = require('mysql');

// 3.创建连接
const conn = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root', //用户
    password: '123456', //密码
    database: 'dbTest' //请确保数据库存在
});
// 4.连接
conn.connect(err => {
    if (err) throw err;
    console.log('连接成功');
});

// 创建表
const CREATE_SQL = `CREATE TABLE IF NOT EXISTS test ( id INT NOT NULL PRIMARY KEY auto_increment, name VARCHAR ( 30 ) )`;
const INSERT_SQL = `INSERT INTO test(name) VALUES(?)`;
const SELECT_SQL = `SELECT * FROM test`;
//查询 conn.query()
conn.query(CREATE_SQL,  (error)=> {
    if (error) throw error;
    conn.query(INSERT_SQL,'hello',(err, result) => {
        if (err) throw err;
        console.log(result);
        conn.query(SELECT_SQL,(err,results)=>{
            console.log(results);
            // 关闭连接
            conn.end(); //若query语句有嵌套,则end需在此执行
        })
    })
});

Sequelize 

Sequelize是一个Node.js ORM(Object-Relational Mapping)框架,支持多种数据库,包括MySQL、PostgreSQL、SQLite和MariaDB等。它提供了一种在Node.js中操作关系型数据库的简单方式,使用JavaScript语言进行操作,可以方便地进行增删改查等操作。

Sequelize主要提供了以下功能:

  1. 定义模型:Sequelize提供了一种定义模型的方式,可以方便地将JavaScript对象映射到数据库中的表,并设置表之间的关系。

  2. 数据查询:Sequelize提供了一种查询构建器,可以方便地进行复杂的查询操作,并支持事务和锁机制。

  3. 数据验证:Sequelize提供了一种数据验证机制,可以在保存数据之前对数据进行验证。

  4. 数据迁移:Sequelize提供了一种数据迁移工具,可以方便地进行数据库结构的变更,支持回滚操作。

总的来说,Sequelize是一个功能丰富、易于使用的ORM框架,可以帮助我们更好地操作关系型数据库。它提供了一种简单的方式来定义模型、查询数据、验证数据和迁移数据等操作,使得我们可以更加高效地进行数据库开发。

const { Sequelize, DataTypes } = require('sequelize')
const Op = Sequelize.Op
// 建立连接
const sequelize = new Sequelize('dbTest', 'root', '', {
  host: '127.0.0.1',
  dialect: 'mysql',
})
;(async function () {
  try {
    await sequelize.authenticate()
    console.log('Connection has been established successfully.')
  } catch (error) {
    console.error('Unable to connect to the database:', error)
  }
})()

// 定义模型
const Books = sequelize.define(
  'Books',
  {
    // 定义表中的字段,对象模型中的属性
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true, //设置主键
      autoIncrement: true,
      comment: '自增的id',
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false, // 不允许为空,默认为true
    },
    price: {
      type: DataTypes.FLOAT,
      allowNull: false,
    },
    count: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
    },
  },
  {
    tableName: 'books',
    // 指定是否创建createAt和updateAt字段,默认true表示创建
    timestamps: false,
    freezeTableName: true,
  }
)

// 模型同步到数据库
Books.sync({ force: true }).then(async () => {
  // CRUD
  // 插入数据 插入一条
  // Books.create({})
  // 插入多条数据
  Books.bulkCreate([
    {
      name: '你不知道的JavaScript',
      price: 2.9,
      count: 10,
    },
    {
      name: 'Vue实战开发',
      price: 100.9,
      count: 100,
    },
    {
      name: 'React实战开发',
      price: 122.9,
      count: 88,
    },
    {
      name: 'Nodejs实战',
      price: 122.9,
      count: 100,
    },
  ])

  //   查询所有的书籍
  const books = await Books.findAll()
  // const books = await Books.findAll({ attributes: ['id', 'name','price'] })
  // 排除某些属性
  // const books = await Books.findAll({
  //   attributes: { exclude: ['count'] },
  //   where: {
  //     price: {
  //       [Op.gt]: 10,
  //     },
  //   },
  //   order: [
  //     ['id', 'DESC'], //根据id倒序
  //   ],
  //   limit: 3,
  // })
  //   更新
  //   books = await Books.update(
  //     { name: '学习node mysql' },
  //     {
  //       where: {
  //         id: 2,
  //       },
  //     }
  //   )
  //   const maxPrice = await Books.max('count')
  //   console.log(maxPrice)
  Books.max('price').then((maxPrice) => console.log(maxPrice))
  await Books.destroy({
    where: {
      id: 1,
    },
  })
  //   console.log('All books', JSON.stringify(books, null, 2))
})

mongodb

MongoDB是一种开源的、面向文档的非关系型数据库管理系统,它使用JSON风格的文档代替了传统的行和列的存储方式。 

安装地址:

Download MongoDB Community Server | MongoDB

配置过程(这个链接比较详细):

详细配置MongoDB

配置完成后将启动方式改为手动启动:

win+R输入cmd打开命令行然后输入services.msc,找到MongoDB改成手动

改成手动之后:

打开管理员命令行输入net start mongodb,启动成功

robo 3t 可视化工具

安装地址:

https://robomongo.org/download

详细链接:

robo 3t安装详情

以上准备完成之后:

打开vscode, 命令行输入安装mongodb

npm install mongodb

// 下载
// mongodb npm i mongodb -S
const MongoClient = require('mongodb').MongoClient

;(async function () {
  const client = new MongoClient('mongodb://127.0.0.1:27017')
  // 链接服务端
  await client.connect()
  console.log('链接成功')

  // 获取数据库 // 获取集合
  const db = client.db('school')
  // 获取模型 grade1
  const grade1 = db.collection('grade1')

  // 先删除所有的数据
  grade1.deleteMany()
  // grade1.insertOne({
  //   name:"张三",age:20,hobby:['吃饭','睡觉','打豆豆'],score:90
  // })
  // grade1.insertMany([]);

  // CRUD
  // 查询操作
  let r = await grade1.insertMany([
    { name: '张三', age: 20, hobby: ['吃饭', '睡觉', '打豆豆'], score: 90 },
    { name: '李四', age: 40, hobby: ['妹子', '篮球'], score: 93 },
    { name: '王五', age: 20, hobby: ['妹子', '睡觉'], score: 70 },
    { name: '赵六', age: 16, hobby: ['妹子'], score: 50 },
    { name: '张丽', age: 38, hobby: ['妹子'], score: 56 },
    { name: '小红', age: 40, hobby: ['妹子'], score: 87 },
    { name: '小马', age: 20, hobby: ['妹子'], score: 79 },
    { name: '小王', age: 59, hobby: ['妹子'], score: 102 },
    { name: '小黑', age: 16, hobby: ['妹子'], score: 60 },
    { name: 'kiki', age: 18, hobby: ['篮球'], score: 49 },
  ])
  //   // 查询文档的操作 获取一条数据
  r = await grade1.findOne({ name: '张三' })
  //   //selert * from grade1
  r = await grade1.find().toArray()
  r = await grade1.find({ name: '张三' }).toArray()
  //   // 比较运算符
  //   r = await grade1
  //     .find({
  //       age: {
  //         // gt大于 lt小于  gte 大于等于  lte小于等于
  //         $gte: 20,
  //       },
  //     })
  //     .toArray()

  //   // 逻辑运算符  $and  $or $ne  $nor 不等于
  //   // 查询姓名叫王五并且年龄为20岁的人
  //   r = await grade1
  //     .find({
  //       name: '王五',
  //       age: 20,
  //     })
  //     .toArray()
  //   // 查询姓名叫张三或者年龄为20岁的人
  //   r = await grade1
  //     .find({
  //       $or: [
  //         {
  //           name: '张三',
  //         },
  //         {
  //           age: 20,
  //         },
  //       ],
  //     })
  //     .toArray()

  //   // // 查询年龄不大于20岁并且age不小于16的人员
  //   r = await grade1
  //     .find({
  //       $nor: [
  //         {
  //           age: {
  //             $gt: 20,
  //           },
  //         },
  //         {
  //           age: {
  //             $lt: 16,
  //           },
  //         },
  //       ],
  //     })
  //     .toArray()

  //   // 正则表达式
  //   r = await grade1
  //     .find({
  //       name: {
  //         $regex: /^张/,
  //       },
  //     })
  //     .toArray()

  //   // $all $in $size
  //   // 查找指定字段包含所有指定内容的数据
  //   r = await grade1
  //     .find({
  //       hobby: {
  //         $all: ['妹子'],
  //       },
  //     })
  //     .toArray()

  //   // 查找指定字段只有指定内容其一的数据
  r = await grade1
    .find({
      hobby: {
        $in: ['妹子', '睡觉'],
      },
    })
    .toArray()

  //   // 查找指定字段的数据有三条的
  //   r = await grade1
  //     .find({
  //       hobby: {
  //         $size: 3,
  //       },
  //     })
  //     .toArray()

  //   // 分页查询  limit()
  //   // 查询前两条数据
  //   r = await grade1.find().limit(2).toArray()

  //   // 跳过前2条数据,获取后4条数据
  //   r = await grade1.find().skip(2).limit(4).toArray()
  //   // 根据age字段进行排序 1表示正序  -1 表示倒序
  //   r = await grade1
  //     .find()
  //     .sort({
  //       age: -1,
  //     })
  //     .toArray()

  //   // 分页
  //   const pageIndex = 1 //当前的索引
  //   const pageSize = 3 //当前一页显示的数据
  //   // 1  2  3 4
  //   r = await grade1
  //     .find()
  //     .skip((pageIndex - 1) * pageSize)
  //     .limit(pageSize)
  //     .toArray()

  //   // // 数组 forEach方法 map()方法
  //   // r.forEach(element => {
  //   //   // console.log(element);

  //   // });
  //   // 所有的名字返回给前端 一个数组
  //   let names = r.map((ele) => ele.age)
  //   // console.log(names);
  //   // 聚合函数 $sum $min $max $avg
  //   // 相同年龄的人数
  r = await grade1
    .aggregate([
      {
        $group: {
          _id: '$age',
          count: {
            $sum: 1,
          },
        },
      },
    ])
    .toArray()

  //   r = await grade1
  //     .aggregate([
  //       {
  //         $group: {
  //           _id: '$age',
  //           avgScore: {
  //             $avg: '$score',
  //           },
  //         },
  //       },
  //     ])
  //     .toArray()
  //   r = await grade1
  //     .aggregate([
  //       {
  //         $group: {
  //           _id: '$age',
  //           avgScore: {
  //             $max: '$score',
  //           },
  //         },
  //       },
  //     ])
  //     .toArray()

  // // 更新文档
  r = await grade1.updateOne(
    {
      name: "张三",
    },
    {
      $set:{
        name:"kiki"
      }
    }
  )
  console.log('更新成功',r )
  // // 当你做删除的时候 一定要问一下自己 是否要删除
  // r = await grade1.deleteOne({
  //   name:'张三'
  // })
  // console.log(r.result);

  // 关闭客户端的链接
  client.close()
})()

mongoose

Mongoose是基于MongoDB的Node.js ORM框架。

Mongoose提供了一些基于Schema的方法,使得我们可以在Node.js中更加方便地操作MongoDB数据库。

Mongoose提供了很多功能,包括数据验证、中间件、查询构建器等,可以帮助我们更方便地操作MongoDB数据库。

因此,我们可以说Mongoose是MongoDB的一个补充,可以更好地发挥MongoDB的优势。

const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1/test')
const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', async () => {
  // we're connected!
  // 定义一个schema =>表
  // 字段
  const blogSchema = new mongoose.Schema({
    title: String,
    author: String,
    body: String,
    comments: [
      {
        body: String,
        date: Date,
      },
    ],
    date: {
      type: Date,
      default: Date.now,
    },
    hidden: Boolean,
    meta: {
      votes: Number,
      favs: Number,
    },
  })
  // 定义实例方法 (schema对象上的方法)
  blogSchema.methods.findAuthor = function () {
    return this.model('Blog').find({ author: this.author }).exec()
  }
  // 定义静态方法 (模型上的方法)
  blogSchema.statics.findTitle = function (title) {
    return this.find({ title: title }).exec()
  }

  // 定义虚拟属性
  blogSchema.virtual('getContent').get(function () {
    return `${this.author}发布了一篇文章叫${this.title}`
  })

  // 定义一个模型
  const Blog = mongoose.model('Blog', blogSchema)
  try {
    await Blog.deleteMany()
    // 后添加
    await Blog.insertMany([
      {
        title: 'Vue基础',
        author: '小尤',
        body: 'Vue是一个轻量级的高效的牛逼前端框架',
        comments: [
          {
            body: '您说的对,非常认同',
            date: new Date(),
          },
        ],
        hidden: true,
        meta: {
          votes: 10,
          favs: 200,
        },
      },
      {
        title: 'React',
        author: 'faceBook',
        body: 'React是更牛逼前端框架',
        comments: [
          {
            body: '您说的似对似不对,不是那么认同',
            date: new Date(),
          },
        ],
        hidden: false,
        meta: {
          votes: 400,
          favs: 2000,
        },
      },
    ]) //插入多条数据
    console.log('插入数据成功')

    // 查询操作
    // find() findOne() findById()
    // let r = await Blog.find({author:'小尤'})
    let r = await Blog.find().and([
      {
        author: 'faceBook',
      },
      {
        title: 'React',
      },
    ])

    // 在下面一定要多看文档,当你的需求是做不同的操作的时候结合文档 进行实现
    let b = new Blog({ author: '小尤' })
    r = await b.findAuthor()
    r = await Blog.findTitle('Vue基础')
    // console.log('更新结果', r)

    // 5e66faf1d7886659dbf85b10

    // 查询一条结果 根据_id获取
    let sid = mongoose.Types.ObjectId('621f83a4cec82e5d1ddb469b')
    r = await Blog.findOne({ _id: sid })

    r = await Blog.findOne({ author: '小尤' })
    console.log(r.getContent)

    // 更新
    // r = await Blog.where({ author: '小尤' }).updateOne({ title: '哈哈哈哈' })
    // console.log('更新结果',r);
    // // 更新并返回当前查询的结果
    r = await Blog.findOneAndUpdate(
      { author: '小尤' },
      { author: 'kikiyo' },
      { new: true }
    )
    console.log('查询结果为', r)

    // 删除操作
    // r = await Blog.deleteOne({ author: '小尤' })
    // console.log('删除成功',r); r.n 如果等于 表示 更新或删除成功

    // 删除
  } catch (error) {
    console.log(error)
  }
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,以下是一份可持续线段树的代码: ``` #include<bits/stdc++.h> using namespace std; const int N=1e5+10; int n,m,op,l,r,c,w[N],root[N],cnt; struct node{ int l,r,sum; }t[N*40]; int build(int l,int r){ int now=++cnt; t[now].sum=0; if(l==r){ return now; } int mid=(l+r)>>1; t[now].l=build(l,mid); t[now].r=build(mid+1,r); return now; } int update(int pre,int l,int r,int x,int k){ int now=++cnt; t[now]=t[pre]; t[now].sum+=k; if(l==r){ return now; } int mid=(l+r)>>1; if(x<=mid){ t[now].l=update(t[pre].l,l,mid,x,k); }else{ t[now].r=update(t[pre].r,mid+1,r,x,k); } return now; } int query(int x,int y,int l,int r,int k){ if(l>=k&&r<=k){ return t[y].sum-t[x].sum; } int mid=(l+r)>>1,ans=0; if(k<=mid){ ans+=query(t[x].l,t[y].l,l,mid,k); } if(k>mid){ ans+=query(t[x].r,t[y].r,mid+1,r,k); } return ans; } int main(){ cin>>n>>m; for(int i=1;i<=n;i++){ scanf("%d",&w[i]); } sort(w+1,w+n+1); int tot=unique(w+1,w+n+1)-w-1; root[0]=build(-1e9,1e9); for(int i=1;i<=n;i++){ root[i]=update(root[i-1],-1e9,1e9,w[i],1); } while(m--){ scanf("%d%d%d",&op,&l,&r); if(op==1){ scanf("%d",&c); int k=lower_bound(w+1,w+tot+1,c)-w-1; printf("%d\n",query(root[l-1],root[r],-1e9,1e9,k)); }else{ ### 回答2: 可持续线段树是线段树的一种改进方法,能够在原线段树的基础上支持多次修改和查询某个历史版本的功能。下面是一份简单的可持续线段树的代码: ```python class Node: def __init__(self, value): self.value = value self.left = None self.right = None class PersistentSegmentTree: def __init__(self, arr): self.version = 0 # 当前版本号 self.arr = arr # 初始数组 self.versions = {0: self.build_tree(0, len(self.arr) - 1, self.arr)} # 版本字典,初始版本构建一棵线段树 def build_tree(self, left, right, arr): if left == right: return Node(arr[left]) # 叶节点 mid = (left + right) // 2 root = Node(0) root.left = self.build_tree(left, mid, arr) root.right = self.build_tree(mid+1, right, arr) root.value = root.left.value + root.right.value # 内部节点存储区间和 return root def update(self, index, value): self.version += 1 new_tree = self.update_recursive(self.versions[self.version - 1], 0, len(self.arr) - 1, index, value) self.versions[self.version] = new_tree def update_recursive(self, root, left, right, index, value): if left == right: return Node(value) mid = (left + right) // 2 new_node = Node(0) if index <= mid: new_node.left = self.update_recursive(root.left, left, mid, index, value) new_node.right = root.right else: new_node.left = root.left new_node.right = self.update_recursive(root.right, mid+1, right, index, value) new_node.value = new_node.left.value + new_node.right.value return new_node def query(self, left, right, version): return self.query_recursive(self.versions[version], 0, len(self.arr) - 1, left, right) def query_recursive(self, root, left, right, query_left, query_right): if query_left <= left and query_right >= right: # 完全包含,直接返回该节点的值 return root.value if query_left > right or query_right < left: # 完全不相交,返回0 return 0 mid = (left + right) // 2 return self.query_recursive(root.left, left, mid, query_left, query_right) + \ self.query_recursive(root.right, mid+1, right, query_left, query_right) ``` 上述代码描述了一个基于数组的可持续线段树,其中包含了构建线段树、更新节点和查询区间的功能。对于每个历史版本,使用版本号作为索引存储在versions字典中。该线段树的时间复杂度为O(logn),其中n为数组长度。 ### 回答3: 可持续线段树是一种用于解决在线算法问题的数据结构,它可以支持对原始线段树的修改,并能够保留每个版本的历史状态。以下是一个简的可持续线段树的代码实现: ```python class Node: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class PersistentSegmentTree: def __init__(self, nums): self.nums = nums self.roots = [self.build(0, len(nums) - 1)] def build(self, left, right): if left == right: return Node(self.nums[left]) mid = (left + right) // 2 left_child = self.build(left, mid) right_child = self.build(mid + 1, right) return Node(left_child.val + right_child.val, left_child, right_child) def update(self, root_index, index, val): new_root = self.clone(self.roots[root_index]) self._update(new_root, index, val, 0, len(self.nums) - 1) self.roots.append(new_root) def _update(self, node, index, val, left, right): if left == right: node.val = val return mid = (left + right) // 2 if index <= mid: node.left = self.clone(node.left) self._update(node.left, index, val, left, mid) else: node.right = self.clone(node.right) self._update(node.right, index, val, mid + 1, right) node.val = node.left.val + node.right.val def query(self, root_index, start, end): return self._query(self.roots[root_index], start, end, 0, len(self.nums) - 1) def _query(self, node, start, end, left, right): if start > right or end < left: return 0 if start <= left and end >= right: return node.val mid = (left + right) // 2 return self._query(node.left, start, end, left, mid) + self._query(node.right, start, end, mid + 1, right) def clone(self, node): return Node(node.val, node.left, node.right) ``` 该代码实现了一个可持续线段树的类`PersistentSegmentTree`,主要包括以下几个方法: - `__init__(self, nums)`: 类的初始方法,接受一个包含初始数据的列表。 - `build(self, left, right)`: 递归构建线段树的方法。 - `update(self, root_index, index, val)`: 对线段树进行更新的方法,指定根节点索引、要更新的位置和新的值。 - `_update(self, node, index, val, left, right)`: 实际进行更新的递归方法。 - `query(self, root_index, start, end)`: 查询指定范围内元素和的方法,指定根节点索引、开始和结束位置。 - `_query(self, node, start, end, left, right)`: 实际进行查询的递归方法。 - `clone(self, node)`: 复制节点的方法。 以上是一个基本的可持续线段树的代码实现,可以根据具体需求进行适当的修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值