38

微信小程序云开发—云函数连接MySQL

 4 years ago
source link: https://aquan.run/archives/微信小程序云开发云函数连接mysql
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

微信小程序云开发—云函数连接MySQL

本文章代码已上传GitHub: https://github.com/aquanlerou/miniprogram-cloud-development

直接上干货,主要是利用微信的云函数和 Sequelize 进行连接外部 MySQL ,本文章主要讲述:

MySQL
MySQL

注:微信小程序APPID(请自行去地址注册 https://mp.weixin.qq.com

拉取我的代码或则创建一个新的云开发小程序

//本文章主要的代码在一下目录中
miniprogram-cloud-development
 ├── cloudfunctions
 │   └── mysql
 ├── miniprogram
 │   └── pages
 │       └── mysql
 ├── project.config.json
 └── README.md

选择已经配置好的 mysql 页面编译模式,在编译器中直接打开 MySQL 页面

我们页面代码也只需要一行代码,按钮进行触发云函数即可。

mysql.wxml

<button bindtap="mysql">mysql</button>

mysql.js

Page({
    mysql: function(event) {
        console.log(event)
		//调用云函数
        wx.cloud.callFunction({
            name: 'mysql' //调用我们后面写的mysql云函数对应命名
        }).then(res => {
            console.log(res)
        })
    }
})

这是我们前端看到的页面了,就一个按钮触发云函数的页面就写好了。

创建连接MySQL云函数

可以看到我的代码中已经创建好一个叫 mysqlindex.js 云函数如下

const cloud = require('wx-server-sdk')

const Sequelize = require('sequelize')
// const sequelize = new Sequelize('数据库名称', '用户名', '密码', {
const sequelize = new Sequelize('xx', 'xx', 'xx', {
    host: '119.28.161.110',//云数据库IP地址
    port: 3306,
    dialect: 'mysql',
    operatorsAliases: false,
    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000
    }
})

//创建USER表,表结构为一个firstName和lastName字段同为String类型
const User = sequelize.define('user', {
    firstName: {
        type: Sequelize.STRING
    },
    lastName: {
        type: Sequelize.STRING
    }
})

cloud.init()

exports.main = async (event, context) => {
	
    //这里进行调用创建USER表,并且插入一条数据,最后返回结果给调用者。
    return await User.sync({ force: true }).then(() => User.create({
        firstName: 'Huangquan',
        lastName: 'Wu'
    })).then(res => {
        return res.toJSON()
    })

}

Sequelize 的文档地址: https://sequelize.org/v4/

下面我们要在个云函数 miniprogram-cloud-development\cloudfunctions\mysql 目录打开终端,安装 Sequelize 的依赖

Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。

D:\Git\miniprogram-cloud-development\cloudfunctions\mysql>npm install --save sequelize
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

+ [email protected]
added 21 packages from 93 contributors and audited 22 packages in 7.577s
found 0 vulnerabilities


D:\Git\miniprogram-cloud-development\cloudfunctions\mysql>npm install --save mysql2
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

+ [email protected]
added 19 packages from 21 contributors and audited 41 packages in 10.162s
found 0 vulnerabilities


D:\Git\miniprogram-cloud-development\cloudfunctions\mysql>

安装好后我们需要把它同步到云开发的环境中,这里就不详细讲解怎么开通创建云开发环境了,可以自行在官方文档进行查找学习

附上地址: https://developers.weixin.qq.com/miniprogram/dev/wxcloud/basis/getting-started.html

测试调用云函数

我们只需要在预先设置的 mysql 编译模式下后,点击我们的按钮观察控制台打印的结果,和数据库可视化工具是否创建了表和插入数据。

PXZcKHULNWow8hY.jpg

zLxQJRFdvV8iNYe.jpg

可以看到我们远端的 MySQL 数据库已经创建了 USER 表并且插入一条数据。

总结

个人比较推荐直接使用云开发自带的数据库,因为速度快,用外连 MySQL 的话会收到网络波动的影响。就像我要把这个云函数的 超时时间跳到15s


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK