Python操作MySQL数据库
来源:互联网 发布:php 判断是否含有中文 编辑:程序博客网 时间:2024/05/14 01:29
1、数据库查询操作
Python查询Mysql使用fetchone()方法获取单条数据,使用fetchall()方法获取多条数据,使用rowcount返回执行execute()方法后影响的行数。
实例:
# -*- coding: UTF-8 -*-import MySQLdbdb = MySQLdb.connect("127.0.0.1", "root", "mysql", "hwd" )# 打开数据库连接cursor = db.cursor()# 使用cursor()方法获取操作游标sql = "select * from user"try: cursor.execute(sql)# 使用execute方法执行SQL语句 print(cursor.rowcount)# 使用rowcount返回执行execute()方法后影响的行数 results = cursor.fetchall() # 使用fetchall()接收全部的返回结果行 for row in results: id = row[0] name = row[1] password = row[2] print(id, name, password)except: print("Error: unable to fecth data")db.close()# 关闭数据库连接
输出结果:
4(1L, 'Tom', '123')(2L, 'Jerry', '456')(3L, 'Diana', '789')(4L, 'Anny', '123456')
2、数据库插入操作
以下实例使用执行SQL INSERT语句向表user插入记录。
# -*- coding: UTF-8 -*-import MySQLdbdb = MySQLdb.connect("127.0.0.1", "root", "mysql", "hwd" )# 打开数据库连接cursor = db.cursor()# 使用cursor()方法获取操作游标id = 5name = "Jack"password = "12345"sql = "insert into user values('%d','%s','%s')" % (id,name,password)# 传递参数try: cursor.execute(sql)# 使用execute方法执行SQL语句 db.commit()# 提交到数据库执行except: db.rollback()# 发生错误时回滚db.close()# 关闭数据库连接
运行结果:
3、数据库更新操作
更新操作用于更新数据表的的数据,以下实例将user表中的id字段为5的password改为‘54321’:
# -*- coding: UTF-8 -*-import MySQLdbdb = MySQLdb.connect("127.0.0.1", "root", "mysql", "hwd" )# 打开数据库连接cursor = db.cursor()# 使用cursor()方法获取操作游标id = 5password = "54321"sql = "update user set password='%s' where id='%d'" % (password,id)# 传递参数try: cursor.execute(sql)# 使用execute方法执行SQL语句 db.commit()# 提交到数据库执行except: db.rollback()# 发生错误时回滚db.close()# 关闭数据库连接
运行结果:
4、删除操作
删除操作用于删除数据表中的数据,以下实例演示了删除数据表user中id等于5的数据:
# -*- coding: UTF-8 -*-import MySQLdbdb = MySQLdb.connect("127.0.0.1", "root", "mysql", "hwd" )# 打开数据库连接cursor = db.cursor()# 使用cursor()方法获取操作游标id = 5sql = "delete from user where id='%d'" % (id)# 传递参数try: cursor.execute(sql)# 使用execute方法执行SQL语句 db.commit()# 提交到数据库执行except: db.rollback()# 发生错误时回滚db.close()# 关闭数据库连接
运行结果:
阅读全文
0 0
- Python操作Mysql数据库
- python操作MySQL数据库
- python操作MySQL数据库
- python操作MySQL数据库
- python操作MySQL数据库
- python操作MySQL数据库
- python操作MySQL数据库
- python操作MySQL数据库
- python操作MySQL数据库
- python操作MySQL数据库
- python 操作mysql 数据库
- python操作mysql数据库
- python 操作 mysql数据库
- python操作MySQL数据库
- python操作MySQL数据库
- Python操作MySQL数据库
- Python操作mysql数据库
- python操作MySQL数据库
- 状态模式
- express入门(8)- 加密
- leetcode 8 String to Integer (atoi)
- Axure RP 8 注册码(亲测可用)
- UML(统一的模型语言)
- Python操作MySQL数据库
- 精选!15 个必备的 VSCode 插件(前端类)
- css选择器
- Android自定义View的实现
- springboot监控actuator使用手册
- InvalidateRect()、UpdateWindow()、RedrawWindow()区别
- Dubbo系列-4.工厂模式的Registry
- jetty: 请求的操作无法在使用用户映射区域打开的文件上执行
- Oracle创建存储过程及在Mybatis中的调用