Python 数据库编程
Python 标准数据库接口为 Python DB-API,它提供了数据库应用编程接口。
Python DB-API 使用流程:
- 引入 API 模块。
- 获取与数据库的连接。
- 执行SQL语句和存储过程。
- 关闭数据库连接。
Python3 通过 pymysql 模块连接 MySQL 数据库,使用 pip3 install PyMySQL 安装模块。
import pymysql # 建立数据库连接 db = pymysql.connect(host='127.0.0.1', user='admin', password='123456', database='test', port=3306, charset='utf8') try: # 创建游标对象 with db.cursor() as cursor: # 执行SQL操作 cursor.execute("SELECT VERSION()") # 提取结果集 data = cursor.fetchall() print("Mysql Version:", data[0][0]) finally: # 关闭数据库连接 db.close()
浙公网安备 33010602011771号