博文配套视频课程:24小时实现从零到AI人工智能
首先下载mysql驱动
C:\Users\Administrator>pip install mysql
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting mysql
Requirement already satisfied: mysqlclient in d:\anaconda3\lib\site-packages (from mysql) (1.4.2.post1)
Installing collected packages: mysql
Successfully installed mysql-0.0.2
python连接mysql数据库
import pymysql
# 连接数据库
db = pymysql.connect(host="127.0.0.1",user="root",password="root",database="mysql")
# connection
print(db)
# 所有的操作都需要通过游标来执行
cursor = db.cursor()
数据插入操作
try:
sql = "insert into article (title, name, url, collection) values (%s,%s,%s,%s)"
# 通过游标完成CRUD
cursor.execute(sql,('我是标题','作者名称','url地址','文艺、科技、娱乐'))
# 默认需要手动提交事务
db.commit()
except:
print('sql插入出错')
db.rollback()
finally:
cursor.close()
db.close()
数据更新操作
cursor = db.cursor()
# 数据的插入操作 db file url 都需要异常的捕获
try:
sql = "update article set title=%s, name=%s where id=%s"
# 返回的是受影响的行数
count = cursor.execute(sql,('新标题2','老作者2',3))
print('更新的行数为',count)
# 默认需要手动提交事务
db.commit()
except:
print('sql更新出错')
db.rollback()
数据查询操作
cursor = db.cursor()
# 数据的插入操作 db file url 都需要异常的捕获
try:
sql = "select * from article where id= %s "
# 返回的是受影响的行数
count = cursor.execute(sql,3)
print('查询的记录数为',count)
# 查询不需要提交事务,但是要通过fetch完成数据的抓取
print(cursor.fetchone())
except:
print('sql查询出错')
查询分页实现
cursor = db.cursor()
try:
keyword = '标题'
current_page = 1
size = 3
sql = "select * from article where title like %s limit %s,%s"
# 返回的是受影响的行数
count = cursor.execute(sql,(f'%{keyword}%',(current_page-1)*size,size))
print('查询的记录数为',count)
# 查询不需要提交事务,但是要通过fetch完成数据的抓取
for row in cursor.fetchall():
print(row)
except:
print('sql查询分页出错')