Skip to main content

Accessing CloudBase MySQL Database Tables in WeChat Mini Program

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

1. Create a MySQL Database Table 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 database table named todos in the Cloud Development Platform, with the field information as follows:

Column NameDescriptionTypeRequiredUnique
idIdentifierintYesYes
is_completedCompletion StatusbooleanNoNo
descriptionDescriptiontextNoNo
titleTitlevarcharNoNo

After creation, enter sample data in the todos table.

2. Create a WeChat Mini Program

3. Install Cloud Development SDK Dependencies

  1. In the directory containing the mini-program's app.json, run the command to install the npm package.
npm install @cloudbase/wx-cloud-client-sdk
  1. Click on the toolbar of the WeChat Developer Tools: "Tools" -> "Build npm".

4. Querying the Data Table from the Mini-Program

  • Initialize the SDK
// app.js
const { init } = require("@cloudbase/wx-cloud-client-sdk");

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

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 db = await getApp().globalData.getDB();
const { data } = await db.from("todos").select("*").range(0, 9);
this.setData({
todos: data,
});
} catch (error) {
console.error("Failed to obtain todo items:", error);
}
},
});
  • Display the 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 to compile and preview the Mini Program.

Notes

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