1.安装pymysql
进行Python连接mysql数据库之前,需要先安装一下pymysql。
直接在终端执行下面的命令即可。
pip install PyMySQL
2.测试是否能连接成功
以下代码实现了连接到一个database,并选择了其中一个表查询所有数据。
import pymysql
# 打开数据库连接
conn = pymysql.connect(host='localhost',
port=3306,
user='root',
passwd='password',
charset = 'utf8'
)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("show databases;")
cursor.execute("use database_name;")
cursor.execute("show tables;")
cursor.execute("select * from tables_name")
# 使用 fetchone() 方法获取单条数据;使用 fetchall() 方法获取所有数据
data = cursor.fetchall()
for item in data:
print