当前位置: 首页 > article >正文

Python对数据库(MySQL,redis、MongoDB)的操作

Python对数据库的操作(MySQL,redis、MongoDB)

一、操作MySQL数据库

安装pymysql:

需要通过pip install pymysql进行安装。

查询数据:fetchone、fetchmany(n)、fetchall()

import pymysql
#建立mysql连接,ip、端口、用户名、密码(passwd,不能写成其他,例如:pwd或者p,否则报错)、库名
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='szz', port=3306, charset='utf8')
#创建游标
cur = conn.cursor(cursor=pymysql.cursors.DictCursor) #指定cursor的类型为字典,返回结果类型是字典,不再是元组
#执行sql,返回值是int,查询出来的结果有几条
cur.execute('select * from test')
#获取第一条数据,游标cur所在的位置为1,游标从0开始,查询结果类型为:字典
row_1 = cur.fetchone()
cur.scroll(0, mode='absolute')  #将游标移动到初始位置
#获取前n行数据
row_2 = cur.fetchmany(n)
cur.scroll(0, mode='absolute')  #将游标移动到初始位置
#获取所有数据,返回结果类型是:list,里面元素是字典
row_3 = cur.fetchall()
cur.scroll(0, mode='absolute')  #将游标移动到初始位置
print(row_2)
#关闭游标
cur.close()
#关闭连接
conn.close()


增加、更新、删除数据

import pymysql
#建立mysql连接
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='szz', port=3306, charset='utf8')
#创建游标
cur = conn.cursor(cursor=pymysql.cursors.DictCursor) #指定cursor的类型为字典,返回结果类型是字典,不再是元组
#执行sql
sql = 'insert into test values(5, "断点", "e10adc3949ba59abbe56e057f20f883e")'
sql_update = 'update test set name="薛之谦" where id=2 '
sql_del = 'delete from test where id = 3'
cur.execute(sql_del)
#insert、update、delete语句需要进行commit,否则无法保证修改或者新建的数据
conn.commit()
#关闭游标
cur.close()
#关闭连接
conn.close()

cursor的相对、绝对位置移动

import pymysql
#建立mysql连接
conn = pymysql.connect(host='192.168.3.66', user='root', passwd='123456', db='szz', port=3306, charset='utf8')
#创建游标
cur = conn.cursor(cursor=pymysql.cursors.DictCursor) #指定cursor的类型为字典,返回结果类型是字典,不再是元组
num = cur.execute('select * from testlhl')
print(num)                      #返回结果是int类型
​
row_1 = cur.fetchone()       # 此时游标的位置在1,数据库取值从0下标开始,获取数据库第一条数据
cur.scroll(2, mode='absolute')   #absolute绝对位置,直接是将游标从0位置移动到指定的位置2
row_2 = cur.fetchone()       #读取数据库第3条数据,游标在3位置
cur.scroll(2, mode='relative')   #relative相对位置,相对于游标当前所在位置,进行移动,移动1位,游标在4位置,若相对移动的位置超过下标,则报out of range
row_3 = cur.fetchone()       #读取第5条数据
#关闭游标
cur.close()
#关闭连接
conn.close()

mysql的增删改查公共方法

def getconn(host, user, passwd, db, sql, port=3306,charset='utf8'):
  conn = pymysql.connect(host=host, user=user, passwd=passwd, port=port, db=db, charset=charset) #建立连接
  cur = conn.cursor(cursor=p

http://www.kler.cn/news/330712.html

相关文章:

  • 24.2.29蓝桥杯|单位换算--8道题
  • 【4.7】图搜索算法-DFS和BFS解根到叶子节点数字之和
  • Linux中的软硬链接和动静态库
  • 大模型压缩3种方式;模型大小的计算;知识蒸馏:利用教师的输入输出,训练调整学生的小模型
  • Linux 中的 Makefile 伪目标详解
  • 【Spring Boot 入门三】Spring Boot与数据库集成 - 构建数据驱动的应用
  • 版本控制-git
  • uniapp中检测应用更新的两种方式-升级中心之uni-upgrade-center-app
  • 产品经理的学习
  • 构建ID3决策树的算法代码 核心部分详细讲解
  • 掌握 C# 异常处理机制
  • STM32堆栈溢出Bug
  • 排序题目:翻转对
  • mac中文件夹怎么显示.git隐藏文件
  • Unraid的cache使用btrfs或zfs?
  • Python 读取与处理出入库 Excel 数据实战案例(HTML 网页展示)
  • 如何使用ssm实现基于web的网站的设计与实现+vue
  • 【有啥问啥】大型语言模型的涌现能力(Emergent Abilities):新一代AI的曙光
  • Android Camera2 与 Camera API技术探究和RAW数据采集
  • 深入理解 Solidity 修饰符(Modifier):功能、应用与最佳实践