1. Install mysql, create a student table and have data. The relevant commands that will be used are as follows:
mysql -u root -p
show tatabases;
use tablename;
show tables;
select * from tablename;
desc tablename;#查看表中数据名称类型等详细信息
2. Install PyMySQl
pip install PyMySQL
备注:安装之前需要先安装好python,当在命令行输入python,命令行输出python版本信息表示python安装成功,然后再执行以上安装命令。
3. After the installation is successful, run the following code on the command line: 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. Check if the connection is successful
运行python test.py后,
控制台因执行了SELECT * from tbstudent会打印出全部学生信息,
表示python和mysql连接成功。