Step 1 创建一个数据库
Step 2 安装mysql-connector-python
pip install mysql-connector-python
Step 3 访问mysql,并查询表
import mysql.connectordef connect_and_query():try:# 连接到MySQL数据库connection = mysql.connector.connect(host='localhost', # 数据库主机地址user='yourusername', # 数据库用户名password='yourpassword', # 数据库密码database='yourdatabase' # 数据库名)if connection.is_connected():db_Info = connection.get_server_info()print("成功连接到MySQL数据库,MySQL 服务器版本为 ", db_Info)cursor = connection.cursor()cursor.execute("select database();")record = cursor.fetchone()