1.安装好mysql,创建学生表且有数据。会使用到的相关命令如下:
mysql -u root -p
show tatabases;
use tablename;
show tables;
select * from tablename;
desc tablename;#查看表中数据名称类型等详细信息
2.安装PyMySQl
pip install PyMySQL
备注:安装之前需要先安装好python,当在命令行输入python,命令行输出python版本信息表示python安装成功,然后再执行以上安装命令。
3.安装成功后,在命令行运行以下代码:python test.py
# -*- coding:utf8 -*-
import pymysql
# 打开数据库连接(ip/数据库用户名/登录密码/数据库名)
db = pymysql.connect(host='localhost',
user='root',
password='123456',
database='student',
port=3306,
charset='utf8')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT * from tbstudent")
date=cursor.fetchall()
for i in date:
print(i)
# 使用 fetchone() 方法获取单条数据.
# data = cursor.fetchone()
# print("Database version : %s " % data)
# 关闭数据库连接
db.close()
4.检查是否将连接成功
运行python test.py后,
控制台因执行了SELECT * from tbstudent会打印出全部学生信息,
表示python和mysql连接成功。