微信小程序连接数据库与WXS的使用

 

🎉🎉欢迎来到我的CSDN主页!🎉🎉

🏅我是Java方文山,一个在CSDN分享笔记的博主。📚📚

🌟推荐给大家我的专栏《微信小程序开发实战》。🎯🎯

👉点击这里,就可以查看我的主页啦!👇👇

Java方文山的个人主页

🎁如果感觉还不错的话请给我点赞吧!🎁🎁

💖期待你的加入,一起学习,一起进步!💖💖

请添加图片描述

前言

      很多同志们再写小程序的过程中,不知道该怎么发起HTTP请求到后端,在Web环境中发起HTTPS请求是很常见的,但是微信小程序是腾讯内部的产品,不能直接打开一个外部的链接。例如,在微信小程序中不能直接打开www.taobao.com网站,但是,在小程序开发的时候,如果需要请求一个网站的内容或者服务,如何实现?虽然微信小程序里面不能直接访问外部链接,但是腾讯为开发者封装好了一个wx.request(object)的API。

一、搭建数据库连接

1.接口地址URL

其他的东西还是基本与我们发送ajax请求一致的。

 为了后期方便维护,我们先将所有的后端接口通过一个文件来保存,在根目录下新建config文件夹随后建立api.js文件。

// 以下是业务服务器API地址
 // 本机开发API地址
 var WxApiRoot = 'http://localhost:8080/wx/';
 // 测试环境部署api地址
 // var WxApiRoot = 'http://192.168.0.101:8070/demo/wx/';
 // 线上平台api地址
 //var WxApiRoot = 'https://www.oa-mini.com/demo/wx/';
 
 module.exports = {
   IndexUrl: WxApiRoot + 'home/index', //首页数据接口
   SwiperImgs: WxApiRoot+'swiperImgs', //轮播图
   MettingInfos: WxApiRoot+'meeting/list', //会议信息
 };

先定义本机开发的API地址,具体的请求在下面定义方便管理。

2.请求方式的封装

 loadMeetingInfos(){
    let that=this;
    wx.request({
        url: api.IndexUrl,
        dataType: 'json',
        success(res) {
          console.log(res)
          that.setData({
              lists:res.data.data.infoList
          })
        }
      })
  }

以上是我们发送请求的代码,虽然比较简短但还是要在需要的地方进行编写,简单的代码反复性高那我们就可以对它进行封装。

在/utils/util.js中添加下列代码

/**
 * 封装微信的request请求
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
      },
      success: function (res) {
        if (res.statusCode == 200) {
            resolve(res.data);//会把进行中改变成已成功
        } else {
          reject(res.errMsg);//会把进行中改变成已失败
        }
      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}

注意在module.exports中导出和需要使用的页面js中使用实const util = require("../../utils/util")

 //首页会议信息的ajax
  loadMeetingInfos() {
    let that = this;
    util.request(api.IndexUrl).then(res => {
      this.setData({
        lists: res.data.infoList
      })
    })
  }

是不是看起来又少了很多代码

3.后端代码

后端SpringBoot搭建的,引入了mysql、mybatisplus、swagger、lombok等依赖。

数据库表结构:

部分代码:

@RestController
@RequestMapping("/wx/home")
public class WxHomeController {
    @Autowired
    private InfoMapper infoMapper;
    @RequestMapping("/index")
    public Object index(Info info) {
        List<Info> infoList = infoMapper.list(info);
        Map<Object, Object> data = new HashMap<Object, Object>();
        data.put("infoList",infoList);
        return ResponseUtil.ok(data);
    }
}

这里我相信大家都懂不必多说!!!!!

 4.前端代码

wxml

<!--index.wxml-->
<view>
  <swiper autoplay="true" indicator-dots="true">
    <block wx:for="{{imgSrcs}}" wx:key="text">
      <swiper-item>
        <view>
          <image src="{{item.img}}" class="swiper-item" />
        </view>
      </swiper-item>
    </block>
  </swiper>
</view>


<view class="mobi-title">
  <text class="mobi-icon"></text>
  <text class="mobi-text">会议信息</text>
</view>
<block wx:for-items="{{lists}}" wx:for-item="item" wx:key="item.id">
  <view class="list" data-id="{{item.id}}">
    <view class="list-img">
      <image class="video-img" mode="scaleToFill" src="{{item.image !=null? item.image : '/static/persons/6.png'}}"></image>
    </view>
    <view class="list-detail">
      <view class="list-title"><text>{{item.title}}</text></view>
      <view class="list-tag">
        <view class="state">{{item.state}}</view>
        <view class="join"><text class="list-num">{{item.num}}</text>人报名</view>
      </view>
      <view class="list-info"><text>{{item.location}}</text>|<text>{{item.starttime}}</text></view>
    </view>
  </view>
</block>
<view class="section">
  <text>到底啦</text>
</view>

wxss

/**index.wxss**/
.section{
  color: #aaa;
  display: flex;
  justify-content: center;
}

.list-info {
  color: #aaa;
}

.list-num {
  color: #e40909;
  font-weight: 700;
}

.join {
  padding: 0px 0px 0px 10px;
  color: #aaa;
}

.state {
  margin: 0px 6px 0px 6px;
  border: 1px solid #93b9ff;
  color: #93b9ff;
}

.list-tag {
  padding: 3px 0px 10px 0px;
  display: flex;
  align-items: center;
}

.list-title {
  display: flex;
  justify-content: space-between;
  font-size: 11pt;
  color: #333;
  font-weight: bold;


}

.list-detail {
  display: flex;
  flex-direction: column;
  margin: 0px 0px 0px 15px;
}

.video-img {
  width: 80px;
  height: 80px;
}

.list {
  display: flex;
  flex-direction: row;
  border-bottom: 1px solid #6b6e74;
  padding: 10px;
}

.mobi-text {
  font-weight: 700;
  padding: 15px;
}

.mobi-icon {
  border-left: 5px solid #e40909;
}

.mobi-title {
  background-color: rgba(158, 158, 142, 0.678);
  margin: 10px 0px 10px 0px;
}

.swiper-item {
  height: 300rpx;
  width: 100%;
  border-radius: 10rpx;
}

.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #aaa;
}

.userinfo-avatar {
  overflow: hidden;
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.usermotto {
  margin-top: 200px;
}

效果展示:

 其实我们这个页面还存在着一些的问题,比如说这个会议的状态不应该显示数字,而是数字对应的状态是什么?参会的人数有多少?会议的时间显示等问题...下面就用wxs带大家解决该问题。

二、WXS的使用

WXS(WeChat Mini Program Storage)是微信小程序提供的本地存储方案,用于在小程序中进行数据的存储和管理。相比远程数据库,WXS更适合于小规模、简单的数据存储需求。

1.wxs 文件

在微信开发者工具里面,右键可以直接创建 .wxs 文件,在其中直接编写 WXS 脚本。

// /pages/comm.wxs

var foo = "'hello world' from comm.wxs";
var bar = function(d) {
  return d;
}
module.exports = {
  foo: foo,
  bar: bar
};
  • exports: 通过该属性,可以对外共享本模块的私有变量与函数。

在需要使用的页面进行引用即可

<wxs src="./../tools.wxs" module="tools" />
<view> {{tools.msg}} </view>
<view> {{tools.bar(tools.FOO)}} </view>

页面输出:

some msg
'hello world' from tools.wxs

学会了基本的wxs的使用,我们在刚刚的页面中进行操作一手。

2.解决数据显示数字问题

function getState(state){
  // 状态:0取消会议1待审核2驳回3待开4进行中5开启投票6结束会议,默认值为1
  if(state == 0 ){
      return '取消会议';
  }else if(state == 1 ){
      return '待审核';
  }else if(state == 2 ){
      return '驳回';
  }else if(state == 3 ){
      return '待开';
  }else if(state == 4 ){
      return '进行中';
  }else if(state == 5 ){
      return '开启投票';
  }else if(state == 6 ){
      return '结束会议';
  }
      
  return '其它';

}

 3.解决统计人数问题

function formatNumber(liexize,canyuze,zhuchiren) {
    var person = liexize+","+canyuze+","+zhuchiren;
    return person.split(',').length;
}

4.解决时间进制问题

function formatDate(ts, option) {
  var date = getDate(ts)
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var week = date.getDay()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  
  //获取 年月日
  if (option == 'YY-MM-DD') return [year, month, day].map(formatNumber).join('-')

  //获取 年月
  if (option == 'YY-MM') return [year, month].map(formatNumber).join('-')

  //获取 年
  if (option == 'YY') return [year].map(formatNumber).toString()

  //获取 月
  if (option == 'MM') return  [mont].map(formatNumber).toString()

  //获取 日
  if (option == 'DD') return [day].map(formatNumber).toString()

  //获取 年月日 周一 至 周日
  if (option == 'YY-MM-DD Week')  return [year, month, day].map(formatNumber).join('-') + ' ' + getWeek(week)

  //获取 月日 周一 至 周日
  if (option == 'MM-DD Week')  return [month, day].map(formatNumber).join('-') + ' ' + getWeek(week)

  //获取 周一 至 周日
  if (option == 'Week')  return getWeek(week)

  //获取 时分秒
  if (option == 'hh-mm-ss') return [hour, minute, second].map(formatNumber).join(':')

  //获取 时分
  if (option == 'hh-mm') return [hour, minute].map(formatNumber).join(':')

  //获取 分秒
  if (option == 'mm-dd') return [minute, second].map(formatNumber).join(':')

  //获取 时
  if (option == 'hh')  return [hour].map(formatNumber).toString()

  //获取 分
  if (option == 'mm')  return [minute].map(formatNumber).toString()

  //获取 秒
  if (option == 'ss') return [second].map(formatNumber).toString()

  //默认 时分秒 年月日
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

 效果展示

 请添加图片描述

到这里我的分享就结束了,欢迎到评论区探讨交流!!

💖如果觉得有用的话还请点个赞吧 💖

### 回答1: const mysql = require('mysql');let connection = mysql.createConnection({ host: 'localhost', user: 'your_username', password: 'your_password', database: 'your_database' });connection.connect(function(err) { if (err) throw err; console.log('Connected!'); }); ### 回答2: 小程序连接MySQL数据库WXS代码: ```javascript // 引入mysql库 var mysql = require('mysql'); // 建立数据库连接 var connection = mysql.createConnection({ host: 'localhost', // 数据库主机地址 user: 'root', // 数据库用户名 password: 'password', // 数据库密码 database: 'mydb' // 数据库名称 }); // 连接数据库 connection.connect(); // 查询数据库中的数据 connection.query('SELECT * FROM mytable', function (error, results, fields) { if (error) { console.log('查询出错:' + error.message); } else { console.log('查询结果:'); console.log(results); } }); // 关闭数据库连接 connection.end(); ``` 上述代码首先引入了mysql库,然后通过`mysql.createConnection`创建一个连接对象,设置数据库的主机地址、用户名、密码和数据库名称,并使用`connection.connect()`连接数据库。 之后使用`connection.query`方法执行一个查询语句,此处的示例查询语句为`SELECT * FROM mytable`,你可以根据实际需要自行调整查询语句。在回调函数中,可以处理查询结果或者打印错误信息。 最后,使用`connection.end()`方法关闭数据库连接。 请注意,为了能够在小程序中使用MySQL数据库,你需要在小程序端配置开发者服务器,将数据库的相关信息配置在服务器代码中。此外,还需要在小程序的`app.json`配置文件中加入`"features": { "miniprogram": true }`。 这段代码仅仅是连接数据库并进行简单的查询操作,实际应用中可能需要更多的数据库操作或错误处理,具体的代码实现还需根据实际项目需求进行调整。 ### 回答3: 在微信小程序中连接MySQL数据库,需要通过后端服务器来进行中转处理,因为小程序前端无法直接连接数据库。下面是一个简单的示例代码: 在后端服务器的代码中,我们使用Node.js和Express来创建一个API用于连接MySQL数据库,并提供数据给小程序端。 ```javascript // server.js const express = require('express'); const mysql = require('mysql'); const app = express(); const port = 3000; const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'yourpassword', database: 'yourdatabase' }); connection.connect((err) => { if (err) throw err; console.log('Connected to MySQL database'); }); app.get('/data', (req, res) => { const query = 'SELECT * FROM yourtable'; connection.query(query, (error, results) => { if (error) throw error; res.json(results); }); }); app.listen(port, () => { console.log(`Server listening on port ${port}`); }); ``` 在小程序端的逻辑代码中,我们使用wx.request方法向后端服务器发送请求,并获取MySQL数据库的数据。 ```javascript // index.js Page({ onLoad: function () { wx.request({ url: 'http://yourserverip:3000/data', method: 'GET', success: (res) => { console.log(res.data); }, fail: (error) => { console.log(error); } }); } }); ``` 确保在小程序的app.json文件中配置了对后端服务器的请求权限: ```json { "permission": { "request": { "url": ["http://yourserverip:3000/"] } } } ``` 另外,可以使用第三方库如mysql模块或ORM框架来进一步简化数据库操作。以上只是一个简单的示例代码,具体的实现会根据实际情况和需求有所不同。
评论 52
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java方文山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值