Python操作MySQL数据库
1、安装
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 = 'select * from player_info_test limit 10' |
| cursor.execute(sql) |
| result = cursor.fetchall() |
| result = cursor.fetchone() |
| result = ccursor.fetchmany(2) |
| 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() |

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 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 梯度及梯度下降