Windows下 Python3.7 访问 Mysql
Python访问Mysql数据库不要太简单:
1.打开Python的安装目录:
2. 使用Python 包管理工具 pip 对Python 包的查找、下载、安装、卸载的功能:
python pip.exe install pyMysql
可以发现pyMysql包已经安装
2.上代码,测试:
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost","root","root","test" )
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT * FROM Student"
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
# 打印结果
print ("id=%s, name=%s" % \
(id, name))
except:
print ("Error: unable to fetch data")
# 关闭数据库连接
db.close()
运行结果: