Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cloud Development Connect to mySQL database


May 22, 2021 Mini Program Cloud Development Advanced



MySQL is arguably the most popular database for Internet enterprises and the most popular related database (cloud development database is document database). If your project already uses MySQL, the database is not easy to migrate to the cloud development database, or your business prefers to use MySQL, in which case you can also use a connection to the self-built MySQL database and pass the data to the small terminal for rendering.

First, private network VPC

1. Comparison between public network and private network access database

Relationship database services purchased by server-built MySQL or cloud service companies such as Tencent Cloud can be connected using cloud functions when external network connectivity and IP whitelisting are open, that is, cloud functions are deployed in public networks and can only access public database resources (intranet or local databases are not available), while your database needs to be accessed by public networks. However, the cloud function does not currently have a fixed IP, so the list of IP whitelists that the database needs to add is longer.

If you don't want your database to be exposed to the public network environment but can be accessed by cloud functions, it is recommended to use Tencent Cloud's private network. T encent cloud products on private networks, such as cloud functions developed by the cloud and The MySQL database of Tencent Cloud, can be connected through the equivalent connections provided by Tencent Cloud. The equivalent connection service has great advantages over public network transmission:

  • Higher quality, sharing the same self-built internal network with other Tencent cloud products, because it is internal transmission, not affected by the quality of the public network, availability, delay, loss rate protection greatly improved;

  • Stronger security, intranet connectivity in the Tencent Group level of anti-DDos security protection, due to not through the wide-area Internet and carrier links, to avoid the risk of message transmission on the public network may be stolen;

  • Intranet transmission is faster, lower cost, cloud function extranet traffic is to be billed, and intranet traffic in the same region is free;

If you want cloud functions developed by the cloud to use resource-consuming services such as graphics images, audio and video processing, and services such as MySQL, Redis, TencentDB, Kafka, which have high security requirements, we recommend using a private network.

2, the creation of private network services

(1) Create a private network for the Shanghai Availability Zone

Tencent cloud console needs to log in, choose WeChat public number (small program account belongs to the public number system) login method, scan the code to select the corresponding small program account to log in.

Open Tencent Cloud Console Private Network Create a private network for free, because the private network has a region property, we need to create a new private network in the domain where the function is located. T he server for cloud functions developed by the cloud is deployed in Shanghai, so the resources in your private network should also be selected in Shanghai. P rivate networks have three core components: private network segment IPv4 CIDR, subnet, and routing tables. S ubnets under a private network can belong to different Availability Zones under that region, and resources within each subnet under the same private network are interoperability by default, whether or not they are in the same Availability Zone. And the initial subnet Availability Zone, you can choose according to your MySQL and other databases in the Availability Zone, if you previously did not have a database in Tencent Cloud, etc., select any Availability Zone in Shanghai can be.

Cloud Development Connect to mySQL database

(2) Purchase MySQL at Tencent Cloud and join the same private network

Buy an instance in MySQL, which opens Tencent's cloud console, and create the instance by finding the private network you created before and the corresponding subnet (pull-down) here.

Cloud Development Connect to mySQL database

(3) Add cloud functions that need to be connected to MySQL to a private network

Open the CloudBase for cloud development in Tencent's cloud development, select the specified environment, then click on the cloud function menu, then create a new cloud function or select a specified cloud function such as mysql, enter the configuration page, click "Edit" in the upper right corner, and select the same private network as the MySQL service in the network configuration. This allows the cloud function to connect to MySQL over a private network.

Cloud Development Connect to mySQL database

Then we can import data or data files into the mysql database as needed or in conjunction with our own business needs, for example, we can import sql files into it using Tencent and the DMS that come with it.

Second, use mysql2 to operate MySQL

1, use mysql2 to connect to MySQL

There are many libraries that support Nodejs connecting to the MySQL database, such as mysql, mysql2, which is recommended here. mysql2 is a Promise writing that supports async / await.

Use the developer tool to open the previous mysql cloud function (as long as the private network can be bound, if not can refer to the previous instructions), add the latest version of mysql2 in package.json, and right-click the cloud function directory to open the input command npm install installation dependency in the terminal:

  1. "dependencies": {
  2. "wx-server-sdk": "latest",
  3. "mysql2": "latest"
  4. }

Then enter the following code in the index.js, and it is important to note that we introduced mysql2/promise, the first parameter .query is sqlString, the string format of the SQL command line statement, and when all database .end otherwise the cloud function will report a timeout error.

  1. const cloud = require('wx-server-sdk')
  2. cloud.init({
  3. env: cloud.DYNAMIC_CURRENT_ENV,
  4. })
  5. const mysql = require('mysql2/promise');
  6. exports.main = async (event, context) => {
  7. try {
  8. const connection = await mysql.createConnection({
  9. host: "10.168.0.7", //内网ip地址
  10. user: "root", //数据库的用户名
  11. password: "tcb123", //数据库密码
  12. database: "tcb", //数据库名称
  13. })
  14. const [rows, fields] = await connection.query(
  15. 'SELECT * FROM `country` WHERE `country` = "china"',
  16. );
  17. connection.end(function(err) { //注意要断开连接,不然尽管获取到了数据,云函数还是会报超时错误
  18. console.log('断开连接')
  19. });
  20. console.log(rows)
  21. console.log(fields)
  22. return rows
  23. } catch (err) {
  24. console.log("连接错误", err)
  25. return err
  26. }
  27. }

Many of the parameters of the mysql2 module are used in line with the mysql module, and more configuration-related information can be viewed in the mysql module technical documentation .

2, mysql2 additions and deletions

mysql2 supports the addition and deletion of the database, the following is a few simple cases, more information can be viewed mysql-related technical documentation:

  1. #创建一个名称为tcb的数据库
  2. CREATE DATABASE `tcb`
  3. #创建一个包含name、address字段的users表格与删除表格
  4. CREATE TABLE `users` (`name` VARCHAR(255), `address` VARCHAR(255))
  5. DROP TABLE `users`
  6. #向users表格里插入记录
  7. INSERT INTO `users`(`name`, `address`) VALUES ('李东bbsky', '深圳')
  8. #查询users表格
  9. SELECT * FROM `users`
  10. #限制查询到的记录数为20,建议记录比较多的数据表查询都需指定limit
  11. SELECT * FROM `users` LIMIT 20
  12. #查询users表格里字段等于某个值的记录
  13. SELECT * FROM `users` WHERE `name` = '李东bbsky'
  14. #将查询结果按名称来排序
  15. SELECT * FROM `users` ORDER BY `name`
  16. #删除满足条件的记录
  17. DELETE FROM `users` WHERE `address` = '深圳'
  18. #更新满足条件的记录的字段值
  19. UPDATE `users` SET `address` = "广州" WHERE `address` = '深圳'
  20. #使用Join进行联表查询
  21. SELECT `users.name` AS `user`, `products.name` AS `favorite` FROM `users` JOIN `products` ON `users.favorite_product` = products.id

3, use serverless-mysql to operate MySQL

A better package serverless-mysql is also recommended below, using the documentation to refer to the serverless-mysql technical documentation

Use the developer tool to open the previous mysql cloud function, add the latest version of mysql2 to package.json, and right-click the cloud function directory to select the input command npm install installation dependency to open in the terminal:

  1. "dependencies": {
  2. "wx-server-sdk": "latest",
  3. "serverless-mysql": "latest"
  4. }

Then enter the following code in the index.js, and it is important to note that we introduced mysql2/promise, the first parameter .query is sqlString, the string format of the SQL command line statement, and when all database .end otherwise the cloud function will report a timeout error.

  1. const cloud = require('wx-server-sdk')
  2. cloud.init({
  3. env: cloud.DYNAMIC_CURRENT_ENV,
  4. })
  5. const mysql = require('serverless-mysql')
  6. exports.main = async (event, context) => {
  7. const connection = await mysql({
  8. config: {
  9. host : "10.168.0.7",//你
  10. database : "country",
  11. user : "root",
  12. password : "lidongyx327"
  13. }
  14. })
  15. let results = await connection.query('INSERT INTO country(Country, Region) VALUES ("中国","亚洲")')
  16. await connection.end()
  17. return results
  18. }

Of course, you can also use Sequelize, an ORM framework .js for .js and io. S pecifically, it highlights a broad support for uniform configuration and query methods. T he databases it supports include PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL. Technical documentation: Sequelize, there are few examples here.

With MySQL in cloud functions, each cloud function is executed with a connection to MySQL's server), but the maximum number of connections to the database is very small (hundreds or thousands), and we can see and set this value in database management max_connections. B ecause the number of connections to the database is relatively small, it is recommended that the addition and deletion of the database be written in a cloud function. This will reduce the probability of cold start of cloud functions and reduce the use of database connections, and the processing of addition and deletion will be centralized into a cloud function, we can use to the cloud function routing tcb-router, which will be described later.

Cloud Development Connect to mySQL database