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

Python基础之数据库操作

一、安装第三方库PyMySQL

1、在PyCharm中通过 【File】-【setting】-【Python Interpreter】搜索 PyMySQL进行安装

2、通过PyCharm中的 Terminal 命令行 输入: pip install PyMySQL

注:通过pip安装,可能会提示需要更新pip,这时可执行:pip install --upgrade pip 进行更新pip

二、mysql数据库查询(SELECT)

1、pymysql.connect()连接数据库

import pymysql
connect = pymysql.connect(host='101.37.246.001', # 数据库地址port= 3306,            # 数据库端口,mysql一般默认为3306user='xxxx',       # 用户名password='xxxx',   # 登录密码database='movie_cat',  # 要连接的数据库名charset='utf8')        # 数据库编码,一般默认utf8

 2、使用 cursor( ) 创建游标

import pymysql
connect = pymysql.connect(host='101.37.246.001', # 数据库地址port= 3306,            # 数据库端口,mysql一般默认为3306user='xxxx',       # 用户名password='xxxx',   # 登录密码database='movie_cat',  # 要连接的数据库名charset='utf8')        # 数据库编码,一般默认utf8
with connect.cursor() as cursor: # 创建游标

3、使用 execute( ) 执行sql语句

 

import pymysql
connect = pymysql.connect(host='101.37.246.001', # 数据库地址port= 3306,            # 数据库端口,mysql一般默认为3306user='xxxx',       # 用户名password='xxxx',   # 登录密码database='movie_cat',  # 要连接的数据库名charset='utf8')        # 数据库编码,一般默认utf8
with connect.cursor() as cursor: # 创建游标 # 创建游标sql = 'SELECT * FROM movie2 'cursor.execute(sql) # 执行sql语句

4、执行sql语句后,需要调用 fetchone() 或 fetchall() 方法来获得查询的返回结果

  • fetchone(): 该方法获取第一个查询结果集。结果集是一个对象,连续多次执行将依次取得下一条结果,直到为空;
  • fetchall(): 接收全部的返回结果行
import pymysql
connect = pymysql.connect(host='101.37.246.001', # 数据库地址port= 3306,            # 数据库端口,mysql一般默认为3306user='xxxx',       # 用户名password='xxxx',   # 登录密码database='movie_cat',  # 要连接的数据库名charset='utf8')        # 数据库编码,一般默认utf8# cursorclass=pymysql.cursors.DictCursor 设置游标返回结果为字典
with connect.cursor() as cursor: # 创建游标sql = 'SELECT * FROM movie2 'cursor.execute(sql) # 执行sql语句data = cursor.fetchall() # 接收全部返回的结果,返回一个元祖类型print(f"数据库查询数据:{data}")print(type(data))
connect.close() # 关闭数据库连接数据库查询数据:((1, 'My Neighbor Totoro', '1988'), (2, 'Dead Poets Society', '1989'), (3, 'A Perfect World', '1993'), (4, 'Leon', '1994'), (5, 'Mahjong', '1996'), (6, 'Swallowtail Butterfly', '1996'), (7, 'King of Comedy', '1999'), (8, 'Devils on the Doorstep', '1999'), (9, 'WALL-E', '2008'), (10, 'The Pork of Music', '2012'), (12, 'huawei', '2020'))
<class 'tuple'>

二、mysql数据库更新数据(UPDATE) 

import pymysql
connect = pymysql.connect(host='101.37.246.001', # 数据库地址port= 3306,            # 数据库端口,mysql一般默认为3306user='xxxx',       # 用户名password='xxxx',   # 登录密码database='movie_cat',  # 要连接的数据库名charset='utf8')        # 数据库编码,一般默认utf8
with connect.cursor() as cursor: # 创建游标sql = 'UPDATE movie2 SET year = 1998 WHERE id = 1 'cursor.execute(sql) # 执行sql语句connect.commit() # 提交数据到数据库
connect.close() # 关闭数据库连接

在cursor( ) 创建游标后通过execute( ) 执行sql,需要通过connect实例调用commit( ) 进行数据提交

三、mysql数据库插入数据(INSERT)

import pymysql
connect = pymysql.connect(host='101.37.246.001', # 数据库地址port= 3306,            # 数据库端口,mysql一般默认为3306user='xxxx',       # 用户名password='xxxx',   # 登录密码database='movie_cat',  # 要连接的数据库名charset='utf8')        # 数据库编码,一般默认utf8
with connect.cursor() as cursor: # 创建游标sql = "INSERT INTO movie2(title, year) VALUES ('firstday', '2021');"cursor.execute(sql) # 执行sql语句connect.commit() # 提交数据到数据库
connect.close() # 关闭数据库连接

 四、mysql数据库删除数据(DELETE)

import pymysql
connect = pymysql.connect(host='101.37.246.001', # 数据库地址port= 3306,            # 数据库端口,mysql一般默认为3306user='xxxx',       # 用户名password='xxxx',   # 登录密码database='movie_cat',  # 要连接的数据库名charset='utf8')        # 数据库编码,一般默认utf8
with connect.cursor() as cursor: # 创建游标sql = "DELETE FROM movie2 WHERE id = 13;"cursor.execute(sql) # 执行sql语句connect.commit() # 提交数据到数据库
connect.close() # 关闭数据库连接

注:insert/delete/update后都需要调用commit( )提交数据到数据库,完成事务提交

封装一个数据库操作类

class ConnectDB:config = {"host":'47.103.126.208',"user":'siyuan',"password":'123456',"database":'mall',"charset":'utf8',#"cursorclass":"pymysql.cursors.DictCursor"}def __init__(self):self.connect = pymysql.connect(**self.config)def select_datas(self, sql):with self.connect.cursor(pymysql.cursors.DictCursor) as cur:cur.execute(sql)data = cur.fetchall()print(data)print(type(data))return datadef charge_datas(self, sql):passdef connect_close(self):self.connect.close()def __call__(self, act=None, sql=None, connect=True):if connect:if act == 'select':datas = self.select_datas(sql)return dataselif act in ['update', 'insert', 'delete']:self.charge_datas(sql)return selfelse:self.connect_close()if __name__ == '__main__':connect_db = ConnectDB()sql = "SELECT * FROM ls_user WHERE nickname LIKE '%思源%';"data1 = connect_db('select', sql)data2 = connect_db('select', sql)connect_db(connect=False)

 

 

 

 

 

 

 

 

 

 

http://www.lryc.cn/news/287875.html

相关文章:

  • redis-发布缓存
  • Stata17安装教程
  • Java PDFBox 提取页数、PDF转图片
  • 【代码随想录14】104.二叉树的最大深度 111.二叉树的最小深度 222.完全二叉树的节点个数
  • AWS 专题学习 P10 (Databases、 Data Analytics)
  • 一键拥有你的GPT4
  • 幻兽帕鲁服务器数据备份
  • 【Digester解析XML文件的三种方式】
  • MATLAB curve fitting toolbox没有怎么办?
  • Linux之快速入门(CentOS 7)
  • Spring框架中的设计模式
  • Java数据结构与算法:邻接矩阵和邻接表
  • 【温故而知新】JavaScript类、类继承、静态方法
  • 小黑艰难的前端啃bug之路:内联元素之间的间隙问题
  • Ubuntu 申请 SSL证书并搭建邮件服务器
  • 视频监控方案设计:EasyCVR视频智能监管系统方案技术特点与应用
  • pyspark.sql.types 中的类型有哪些
  • 开源CRM客户管理系统-FeelCRM
  • Linux创建新分区挂载后普通用户没有读写权限
  • 清越 peropure·AI 国内版ChatGP新功能介绍
  • 力扣1027. 最长等差数列
  • GraphicsMagick 的 OpenCL 开发记录(二十三)
  • 通过Android Logcat分析firebase崩溃
  • 【AI大模型】WikiChat超越GPT-4:在模拟对话中事实准确率提升55%终极秘密
  • 【C语言刷题系列】水仙花数的打印及进阶
  • ICSpector:一款功能强大的微软开源工业PLC安全取证框架
  • HCIA——29HTTP、万维网、HTML、PPP、ICMP;万维网的工作过程;HTTP 的特点HTTP 的报文结构的选择、解答
  • 面试经典题---3.无重复字符的最长子串
  • 使用Robot Framework实现多平台自动化测试
  • Java基础进阶02-xml