一、依赖库的安装
pip3 install pymysql
pip3 install cryptography
二、测试代码
#!/usr/bin/python3
import pymysql
import cryptography
# 打开数据库连接
db = pymysql.connect("localhost","root","123","TEST" )
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print ("Database version : %s " % data)
# 关闭数据库连接
db.close()
三、查询代码:
import pymysql
import cryptography
# 打开数据库连接
db = pymysql.connect("localhost","root","123","TEST" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT * FROM BOOKS"
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
print(name)
except:
print ("Error: unable to fetch data")
finally:
db.close()
四、插入代码:
#!/usr/bin/python3
import pymysql
import cryptography
# 打开数据库连接
db = pymysql.connect("localhost","root","123","TEST" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql = "INSERT INTO BOOKS (NAME) VALUES('%s')" % ('John')
try:
# 执行SQL语句
cursor.execute(sql)
db.commit()
except:
db.rollback()
finally:
db.close()