更新时间:2022-04-08 GMT+08:00
函数如何访问MySQL数据库?
本章介绍如何访问MySQL数据库,具体操作步骤如下:
- 确认MySQL数据库是否搭建在VPC网络中?
- 是,为函数设置与MySQL数据库相同的VPC、子网,具体请参考函数配置VPC。
- 否,MySQL数据库搭建在公网中,获取MySQL数据库的公网IP地址。
- 在函数中,编写对接MySQL数据库的代码,示例如下。
- 创建一个函数,在“代码”页签,为此函数添加pymysql依赖包,如图1所示。
- 编辑以下代码,对接MySQL数据库。
# -*- coding:utf-8 -*- import pymysql.cursors def handler (event, context): # Connect to the database connection = pymysql.connect(host='host_ip', user='user', password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: # Create a new record sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('webmaster@python.org', 'very-secret')) # connection is not autocommit by default. So you must commit to save # your changes. connection.commit() with connection.cursor() as cursor: # Read a single record sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" cursor.execute(sql, ('webmaster@python.org',)) result = cursor.fetchone() print(result) finally: connection.close() output = '^_^' return output
父主题: 函数访问外部资源
函数访问外部资源所有常见问题
more
