爬虫-Python操作MySQL数据库

Python操作MySQL数据库

1、安装

pip install pymysql

2、连接数据库

使用connect函数创建连接对象,此连接对象提供关闭数据库、事务提交、事物回滚等操作。

import pymysql
conn = pymysql.connect(
host='127.0.0.1',
user='xxx',
password='xxxx',
port=3306,
database='test'
)

3、主要方法

方法 功能
cursor() 获取游标对象,操作数据库
commit() 提交事务
rollback() 回滚事务
close() 关闭数据库连接

4、操作数据库

查询操作

# 创建游标,查询数据以元组形式返回
cursor = conn.cursor()
# 创建游标,查询数据以字典形式返回
cursor = conn.cursor(pymysql.cursors.DictCursor)
# 查询的SQL语句
sql = 'select * from player_info_test limit 10'
cursor.execute(sql)
result = cursor.fetchall() # 返回所有数据
result = cursor.fetchone() # 返回一行数据
result = ccursor.fetchmany(2) # fetchmany(size) 获取查询结果数据集中指定数量的记录,默认为1
print(result)
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

插入操作

插入操作中参数可以以元组、列表和字典形式传入,需要用到占位符"%s",注意这个只是占位符,不同于python中的转换说明符。

# 元组、列表形式传参
sql = 'insert into test(ID,NAME,AGE) VALUES(%s,%s,%s)'
cursor.execute(sql,("999","lili",23))
conn.commit()
cursor.close()
conn.close()
# 字典形式传参
sql = 'insert into test(ID,NAME,AGE) VALUES(%(id)s,%(name)s,%(age)s)'
cursor.execute(sql,{"id":"111","name":"Mike","age":28})
conn.commit()
cursor.close()
conn.close()

批量插入操作

sql='insert into test(ID,NAME,AGE) VALUES(%s,%s,%s)'
val=[
(4,'李四',20),
(5,'Jack',22),
(6,'Tom',21)
]
cursor.executemany(sql,val)
conn.commit()
print(mycursor.rowcount,'记录插入成功')

更新操作

sql = 'updata test set NAME=%s where ID = %s'
cursor.execute(sql, ['liu', '999998'])
conn.commit()
cursor.close()
conn.close()

删除操作

sql = 'delete from test where ID = %s'
try:
cursor.execute(sql, ['999999'])
conn.commit()
except Exception as e:
conn.rollback()
print(e)
finally:
cursor.close()
conn.close()

image-20240525114040969

posted @   同淋雪  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
历史上的今天:
2023-05-25 反向传播
2023-05-25 Softmax
2023-05-25 常见LOSS函数之MSE
2023-05-25 多层感知机的梯度推导
2023-05-25 单层感知机的梯度推导
2023-05-25 激活函数及其梯度
2023-05-25 梯度及梯度下降
点击右上角即可分享
微信分享提示