插入操作
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='123456', db='python', port=3306)
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 插入数据
# 编写sql查询语句
sql_insert = """insert into user(userid,username,password) values(1,'老王','123456')"""
# 执行sql语句
cursor.execute(sql_insert)
# 提交操作
db.commit()
查询操作
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='123456', db='python', port=3306)
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 查询操作
# 编写sql查询语句
sql = 'select * from user'
# 执行sql语句
cursor.execute(sql)
results1 = cursor.fetchall()
print(results1)
更新操作
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='123456', db='python', port=3306)
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 更新操作
# 编写sql更新语句
sql_update = "update user set username = '{}' where userid='{}'"
# 执行sql语句
cursor.execute(sql_update.format('老赵',1))
#提交操作
db.commit()
删除操作
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='123456', db='python', port=3306)
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 删除操作
# 编写sql语句
sql_delete = "delete from user where userid = {}"
# 执行sql语句
cursor.execute(sql_delete.format(1))
# 提交操作
db.commit()