要使用Python连接MySQL数据库,你可以选择使用官方的MySQL Connector或者第三方库如PyMySQL。以下是使用这两种库连接MySQL数据库的基本步骤:
使用MySQL Connector
1. 安装MySQL Connector
使用pip安装MySQL Connector Python:
pip install mysql-connector-python
2. 连接数据库
import mysql.connector连接数据库db = mysql.connector.connect(host="数据库地址",user="用户名",password="密码",database="数据库名",charset="utf8" 设置编码方式)创建游标对象cursor = db.cursor()执行SQL查询cursor.execute("SELECT * FROM 表名")获取查询结果result = cursor.fetchall()关闭游标和数据库连接cursor.close()db.close()

使用PyMySQL
1. 安装PyMySQL
使用pip安装PyMySQL:
pip install PyMySQL
2. 连接数据库
import pymysql连接数据库db = pymysql.connect(host="数据库地址",user="用户名",password="密码",database="数据库名",charset="utf8" 设置编码方式)创建游标对象cursor = db.cursor()执行SQL查询cursor.execute("SELECT * FROM 表名")获取查询结果result = cursor.fetchall()关闭游标和数据库连接cursor.close()db.close()
请确保在连接时指定正确的字符集,如`charset="utf8"`,以避免中文显示乱码问题。
