07-python链接mysql
2024-09-16 10:25:07
python3 中使用的是 PyMySQL模块, 取代了之前的 MysqlDB 模块, 其实使用都是一样的,
如果没有该模块的, 需要使用pip命令进行安装
pip install PyMySQL
安装完成以后, 就可以使用了
1, 获取链接
import pymysql # 创建链接
conn = pymysql.connect(host = 'localhost', user = 'root', passwd = '', db = 'python') # 获取cursor游标
cursor = conn.cursor() # 执行sql
result = cursor.execute('select * from user_info') # 获取结果集
userList = cursor.fetchall() # 关闭连接
cursor.close()
conn.close() print(userList)
2, mysql的 CRUD操作
其中 CRUD操作, 需要mysql的事务操作, python已经封装好了, 只需要connect.commit() 和 connect.rollback() 既可了
插入操作:
import pymysql conn = pymysql.connect('localhost', 'root', '', 'python')
cur = conn.cursor() # 带参数的sql, 防sql注入, 各种类型都是 %s, 不区分啥类型的
sql = 'insert into user_info values(%s, %s, %s, %s)'
params = ('', 'vini', 'bj', '') result = cur.execute(sql, params) # 事物提交
conn.commit() cur.close()
conn.close()
修改:
#!/usr/bin/env python3
#coding:utf-
'''
mysql修改操作
''' import pymysql connect = pymysql.connect('localhost', 'root', '', 'python')
cursor = connect.cursor() sql = 'update user_info set age = %s where id = %s'
params = ('', '')
try :
cursor.execute(sql, params)
connect.commit()
except:
connect.rollback()
finally:
cursor.close()
connect.close()
修改删除类似:
最新文章
- 正确解读free -m
- 在IHttpHandler中获取session
- server2003中看不到网上邻居内容,其他电脑无法通过计算机名和IP访问本计算机(但网上邻居中可访问到)
- 算法(第4版)-1.5 案例研究:union-find算法
- C# 获取本机指定类型指定网卡的Ip地址
- WinForm发布程序方式选择
- 岁末年初3Q大战惊现高潮,360震撼推出Android ";3Q"; IM即时通讯
- cordova android platform cordova build 遇到的问题
- PHP5与MySQL数据库操作
- C#中treeview的问题,如何区分根节点和子节点以及根节点和根节点的兄弟节点?
- 在HTML中优雅的生成PDF
- Bluetooth Low Energy介绍
- http://www.cnblogs.com/xqin/p/4862849.html
- Chrome 实用调试技巧
- 成为JavaGC专家(2)—如何监控Java垃圾回收机制
- docker 容器扩盘
- Python经常使用第三方工具、库、骨架
- android脚步---跟随手指动的小球
- matlab switch case 和 try catch用法示例
- CN_Week1_Receptive_Field