Skip to main content

Accessing CloudBase MySQL Cloud Database in WeChat Mini Program

Learn how to create a CloudBase MySQL data model, add sample data, and query data from WeChat Mini Program.

1. Create MySQL Data Model and Add Data

Note: You must log in to the CloudBase platform using the Tencent Cloud account associated with your WeChat Mini Program.

Create a data model named todos in the Cloud Development Console with the following field information:

Field NameField IDData TypeRequiredUnique
Is Completedis_completedBooleanNoNo
DescriptiondescriptionText, Multiline TextNoNo
TitletitleText, Single Line TextNoNo

After creation, enter sample data in the todos data model.

2. Create WeChat Mini Program

3. Install Cloud Development SDK Dependencies

  1. In the directory where the mini-program's app.json is located, execute the command to install the npm package.
npm install @cloudbase/wx-cloud-client-sdk
  1. Click "Tools" -> "Build npm" in the toolbar of the WeChat Developer Tools.

4. Query Data from the Mini Program

  • Initialize the SDK
// app.js

const { init } = require("@cloudbase/wx-cloud-client-sdk");

App({
onLaunch() {
let client = null;
this.globalData.getModels = async () => {
if (!client) {
wx.cloud.init({
env: "<CloudBase environment ID>",
});
client = init(wx.cloud);
}
return client.models;
};
},

globalData: {},
});
  • Add the following query code in the page's js file
// pages/index/index.js

Page({
data: {
todos: [],
},
onLoad() {
this.fetchTodos();
},
async fetchTodos() {
try {
const models = await getApp().globalData.getModels();
const { data } = await models.todos.list({
filter: {
where: {},
},
pageSize: 10,
pageNumber: 1,
getCount: true,
// envType: pre staging environment, prod production environment
envType: "prod",
});
this.setData({
todos: data.records,
});
} catch (error) {
console.error("Failed to get todos:", error);
}
},
});
  • Display data in the corresponding page's wxml file
<!--pages/index/index.wxml-->

<view>
<block wx:for="{{todos}}" wx:key="_id">
<text>{{item.title}}</text>
</block>
</view>

5. Run the Mini Program

In the WeChat Developer Tools, click Compile and Preview to run the Mini Program.

Notes

  • Replace <CloudBase environment ID> with your actual CloudBase environment ID.