pymysql库对数据库进行查询
import pymysql
# 和数据库创建连接
# host:需要连接的数据库地址;port:端口号;database:数据库
conn = pymysql.Connect(host='127.0.0.1', port=3306, database='books',
user='root', password='root', charset='utf8')
# 创建对象
cursor = conn.cursor()
# 发送sql语句
sql = 'select * from t_book'
# 执行sql语句
cursor.execute(sql)
# 结果获取,获取所有结果
rows = cursor.fetchall()
# print('所有结果:', rows)
# 遍历每一个数据
for row in rows:
print(row)
# 结果获取,获取行数
print('响应结果行数:', cursor.rowcount)
# 资源释放
cursor.close()
conn.close()
pymysql库对数据库进行增加
import pymysql
# 创建连接
conn = pymysql.Connect(host='127.0.0.1', port=3306, database='books',
user='root', password='root', charset='utf8', autocommit=True)
# 创建对象
cursor = conn.cursor()
# 发送 sql
sql = "insert into t_book values(4,'水浒传','2021-03-13',100,50,0)"
cursor.execute(sql)
print('新增的行数:', cursor.rowcount)
cursor.execute('select * from t_book')
rows = cursor.fetchall()
for row in rows:
print(row)
# 释放资源
cursor.close()
conn.close()
pymysql库对数据库进行删除
import pymysql
conn = pymysql.Connect(host='127.0.0.1', port=3306, database='books',
user='root', password='root', charset='utf8', autocommit=True)
cursor = conn.cursor()
sql = "delete from t_book where id=4"
cursor.execute(sql)
print('删除的行数:', cursor.rowcount)
cursor.close()
conn.close()
pymysql库对数据库进行修改
import pymysql
conn = pymysql.Connect(host='127.0.0.1', port=3306, database='books',
user='root', password='root', charset='utf8', autocommit=True)
cursor = conn.cursor()
sql = "update t_book set title='西游记后传' where id=4"
cursor.execute(sql)
print('修改的行数:', cursor.rowcount)
cursor.execute('select * from t_book')
rows = cursor.fetchall()
for row in rows:
print(row)
cursor.close()
conn.close()