小程序.云开发入门(二):数据库初次尝鲜之增删改查

之前一节然我们认识了云开发的配置,申请,这一节则进行云开发中数据库的操作,打开云控制台,进行数据库的创建,这里我们创建了名称为todos的集合,具体数据库的介绍我们可以去查看官方介绍传送门

2-1.png

数据库创建完成,则我们就可以进行接下来数据库的则删改查的编写了,我们在项目中相关页面的创建和注册


2-2.png

app.json页面的注册:

{
  "pages": [
    "pages/databaseControl/databaseControl",
    "pages/query/query",
    "pages/index/index",
    "pages/userConsole/userConsole",
    "pages/storageConsole/storageConsole",
    "pages/databaseGuide/databaseGuide",
    "pages/addFunction/addFunction",
    "pages/deployFunctions/deployFunctions",
    "pages/chooseLib/chooseLib",
    "pages/addData/addData"
  ],
  "window": {
    "backgroundColor": "#F6F6F6",
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#F6F6F6",
    "navigationBarTitleText": "云开发 QuickStart",
    "navigationBarTextStyle": "black"
  }
}

页面注册完成进行控制页面的编写,页面会包含增加数据,查看数据,修改数据,删除数据四个功能分类:
databaseControl.wxml

<view class='container'>

  <text>数据库数据操作</text>
  <button class='btn_add' bindtap='onAddData'>添加数据</button>
  <button class='btn_add' bindtap='onQuery'>查询数据</button>
  <button class='btn_add' bindtap='onDelete'>删除数据</button>
  <button class='btn_add' bindtap='onUpdate'>修改数据</button>
</view>

databaseControl.wxss

/* pages/databaseControl/databaseControl.wxss */

.item_style {
  margin-top: 20rpx;
  width: 95%;
  display: flex;
  flex-direction: row;
  align-items: center;
  border: 1px solid #eee;
  border-radius: 5rpx;
  padding: 10rpx;
}

item_style_clo {
  margin-top: 20rpx;
  width: 95%;
  display: flex;
  flex-direction: column;
  border: 1px solid #eee;
  border-radius: 5rpx;
  padding: 10rpx;
}
.input{
  margin-left: 5rpx;
}

.btn_add{
  width: 95%;
  margin-top: 20rpx;
}

databaseControl.js

// pages/databaseControl/databaseControl.js

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {},
  // 新增数据
  onAddData() {
    wx.navigateTo({
      url: '/pages/addData/addData',
    })
  },

  // 查询操作
  onQuery() {
    wx.navigateTo({
      url: '/pages/query/query',
    })
  },

  // 删除操作
  onDelete() {
    wx.navigateTo({
      url: '/pages/query/query?flag_delete=' + false+"&flag_update=" + true,
    })
  },
  //修改操作
  onUpdate() {
    wx.navigateTo({
      url: '/pages/query/query?flag_update=' + false  +"&flag_delete=" + true,
    })
  }

})

编译项目我们可以看到现在页面


2-3.png

数据的新增

操作数据的新增,我们可以在addData里边进行,我们就以添加用户信息为例:
addData.wxml

<!--pages/databaseControl/databaseControl.wxml-->
<view class='container'>


  <text class='title'>个人信息</text>
  <view class='item_style'>
    姓名:
    <input class='input' type='text' bindinput='inputChangedName' placeholder='输入姓名'> </input>
  </view>


  <view class='item_style'>
    年龄:
    <input class='input' type='number' bindinput='inputChangedAge' placeholder='输入年龄' maxlength='3'> </input>
  </view>


  <view class='item_style'>
    性别:
    <input class='input' type='text' bindinput='inputChangedSex' placeholder='输入性别' maxlength='1'> </input>
  </view>

  <view class='item_style'>
    地址:
    <input class='input' type='text' bindinput='inputChangedAddress' placeholder='输入地址' maxlength='25'> </input>
  </view>

  <view class='item_style_clo'>
    爱好:

    <checkbox-group bindchange="checkboxChanged">
      <label wx:for='{{hobbys}}'>
        <checkbox value='{{item.value}}' /> {{item.name}}
      </label>
    </checkbox-group>
  </view>
  <button class='btn_add' bindtap='addData'>添加数据</button>
</view>

addData.wxss

/* pages/databaseControl/databaseControl.wxss */

.item_style {
  margin-top: 20rpx;
  width: 95%;
  display: flex;
  flex-direction: row;
  align-items: center;
  border: 1px solid #eee;
  border-radius: 5rpx;
  padding: 10rpx;
}

item_style_clo {
  margin-top: 20rpx;
  width: 95%;
  display: flex;
  flex-direction: column;
  border: 1px solid #eee;
  border-radius: 5rpx;
  padding: 10rpx;
}
.input{
  margin-left: 5rpx;
}

.btn_add{
  width: 95%;
  margin-top: 20rpx;
}

addData.js

// pages/addData/addData.js
const app=getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    openid: '',
    counterId: '',
    count: 0,
    username: '',
    age: 0,
    sex: '',
    address: "",
    hobbys: [{
      name: '篮球',
      value: 'basktball',
      checked: true,
    }, {
      name: '足球',
      value: 'football'
    }, {
      name: '乒乓球',
      value: 'pingpang'
    }, {
      name: '羽毛球',
      value: 'yumao'
    }, ],
    checkHb: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (app.globalData.openid) {
      this.setData({
        openid: app.globalData.openid
      })
    }
  },

  inputChangedName(e) {
    this.setData({
      username: e.detail.value
    })
  },

  inputChangedAge(e) {
    this.setData({
      age: e.detail.value
    })
  },

  inputChangedSex(e) {
    this.setData({
      sex: e.detail.value
    })
  },

  inputChangedAddress(e) {
    this.setData({
      address: e.detail.value
    })
  },

  checkboxChanged(e) {
    console.log(e.detail.value)
    this.setData({
      checkHb: e.detail.value
    })
  },

  addData: function(e) {
    if (!(this.data.username != '' && this.data.address != '' && this.data.sex != '' && this.data.age != 0)) {
      wx.showToast({
        title: '输入内容不能为空',
        icon: 'none',
      })
      return
    }

    const db = wx.cloud.database()
    db.collection('todos').add({
      data: {
        username: this.data.username,
        age: this.data.age,
        sex: this.data.sex,
        address: this.data.address,
        checkHb: this.data.checkHb
      },
      success: res => {
        // 在返回结果中会包含新创建的记录的 _id
        this.setData({
          counterId: res._id,
          count: 1
        })
        wx.showToast({
          title: '新增记录成功',
        })
        console.log('[数据库] [新增记录] 成功,记录 _id: ', res._id)

        wx.redirectTo({
          url: '/pages/query/query',
        })
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
        console.error('[数据库] [新增记录] 失败:', err)
      }
    })
  }
})

对于数据的上传这里写的有点儿啰嗦,可以使用另一种方法进行,那就是表单格式去提交信息,之后会在信息的修改上使用,编译项目运行结果:


2-4.png

我们可以进行信息的填写和添加,添加完成猴我们可以在云开发控制台数据库查看我们新增的数据;
在这里我们着重的注意的是操作数据添加的方法

 const db = wx.cloud.database()
    db.collection('todos').add({
      data: {
        username: this.data.username,
        age: this.data.age,
        sex: this.data.sex,
        address: this.data.address,
        checkHb: this.data.checkHb
      },
      success: res => {
        // 在返回结果中会包含新创建的记录的 _id
        this.setData({
          counterId: res._id,
          count: 1
        })
        wx.showToast({
          title: '新增记录成功',
        })
        console.log('[数据库] [新增记录] 成功,记录 _id: ', res._id)

        wx.redirectTo({
          url: '/pages/query/query',
        })
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
        console.error('[数据库] [新增记录] 失败:', err)
      }
    })

数据的查询,修改,删除

query.wxml

<!--pages/query/query.wxml-->
<view class='container'>
  <block wx:for='{{queryResult}}'>
    <form class='item' bindsubmit='updataData' id='{{item._id}}'>
      <view class='item_child'>
        姓名:
        <input class='input_style' type='text' value='{{item.username}}' maxlength='5' name="username"></input>
      </view>
      <view class='item_child'>
        年龄:
        <input class='input_style' type='number' value='{{item.age}}' maxlength='3' name='age'></input>
      </view>
      <view class='item_child'>
        性别:
        <input class='input_style' type='text' value='{{item.sex}}' maxlength='4' name='sex'></input>
      </view>
      <view class='item_child'>
        地址:
        <input class='input_style' type='text' value='{{item.address}}' maxlength='20' name='address'></input>
      </view>
      <view class='item_child'>
        <button class='btn' id='{{item._id}}' bindtap='deleteData' hidden='{{flag_delete}}'>删除数据</button>
        <button class='btn' form-type='submit' hidden='{{flag_update}}'>修改数据</button>
      </view>
    </form>
  </block>
</view>

query.js

// pages/query/query.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    queryResult: "",
    openid: '',
    username: '',
    age: 0,
    sex: "",
    address: '',
    _id: '',
    flag_update: true,
    flag_delete: true,
    title: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    if (options.flag_update == 'false') {
      that.setData({
        flag_update: false
      })
    }
    if (options.flag_delete == 'false') {
      that.setData({
        flag_delete: false
      })
    }

    if (app.globalData.openid) {
      that.setData({
        openid: app.globalData.openid,
      })
    }
    // console.log(options.flag_delete)
    // console.log(options.flag_update)
    that.onQuery()
  },

  // 查询数据
  onQuery: function() {
    console.log(this.data.flag_update)
    console.log(this.data.flag_delete)
    const db = wx.cloud.database()
    // 查询当前用户所有的 todos
    db.collection('todos').where({
      _openid: this.data.openid
    }).get({
      success: res => {
        this.setData({
          queryResult: res.data
        })
        console.log('[数据库] [查询记录] 成功: ', res)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败:', err)
      }
    })
  },


  // 删除数据
  deleteData(e) {
    var that = this
    console.log(e)
    const db = wx.cloud.database()
    db.collection('todos').doc(e.target.id).remove({
      success: res => {
        wx.showToast({
          title: '删除成功',
        })
        that.setData({
          _id: '',
        })

        that.onQuery()
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '删除失败',
        })
        console.error('[数据库] [删除记录] 失败:', err)
      }
    })

  },

  // 更新数据
  updataData(e) {
    console.log(e)
    var that = this

    //获取表单信息
    that.setData({
      username: e.detail.value.username,
      age: e.detail.value.age,
      sex: e.detail.value.sex,
      address: e.detail.value.address,
      _id: e.target.id

    })
    //更新数据
    that.updata()
  },

  //更新数据的方法
  updata() {
    const db = wx.cloud.database()
    var that = this
    db.collection('todos').doc(this.data._id).update({
      data: {
        username: that.data.username,
        age: that.data.age,
        sex: that.data.sex,
        address: that.data.address
      },
      success: res => {
        wx.showToast({
          title: '新增记录成功',
        })
        console.log('[数据库] [新增记录] 成功,记录 _id: ', res._id)
      },
      fail: err => {
        icon: 'none',
        console.error('[数据库] [更新记录] 失败:', err)
      }
    })
  },
})

query.wxss

/* pages/query/query.wxss */


.item{
  width: 95%;
  margin: 10rpx;
  padding: 10rpx;
  display: flex;
  flex-direction: column;
  border: 1px solid #eee;
  border-radius: 10px;
}

.item_child{
  display: flex;
  flex-direction: row;
  margin-top: 5rpx;
  margin-bottom: 5rpx;
}

.input_style{
  background: #eee;
  width: 80%;
  padding: 5rpx;
}

.btn{
  width: 95%;
  margin: 10rpx;

}

在当前页面我们整合查询,修改,删除于一个页面,针对在控制页不同功能进行不同的展示;


2-5.png

2-6.png

2-7.png

至此我们需要注意的是如何进行数据的修改,查询,删除,在代码中都已详细写出!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容