Python学习笔记-操作数据库

news2025/2/28 3:09:37

记述python中关于数据库的基本操作。

一、数据库编程接口

1.连接对象

数据库连接对象(Connection Object)提供获取数据库游标对象、回滚事物的方法,以及连接、关闭数据库连接。

1.1 获取连接对象

使用connect()方法获得连接对象,不同的数据库有不同的参数。

connect()函数常用参数及说明(具体参数以数据库模块为准)
参数说明
dsn数据源名称,给出该参数表示数据库依赖
user用户名
password用户密码
host主机名
database数据库名称

1.2 连接对象方法

连接对象方法
方法说明
close()关闭数据库
commit()

提交事务

主要用于处理数据量大,复杂度搞的数据,如一些列的操作,使用事务可以保证操作全部执行,要么全部不执行。

rollback()回滚事务
cursor()获取游标对象,操作数据库,如执行DML操作,调用存储过程等

2. 游标对象

游标对象(Cursor Object)代表数据库中的游标,用于进行数据库操作,执行sql语句,调用存储过程,增删改查等。

  • 通过连接对象的cursor()方法获取游标对象,需要先连接
  • description:数据库列类型和值的描述信息
  • rowcount:返回结果的行数统计信息,如SELECT、UPDATE、CALLPROC等
游标对象方法
方法说明
callproc(procname[,parameter])调用存储过程,需要数据库支持
close()关闭当前游标
execute(operation[,parameter])执行数据库操作,sql语句或者数据库命令
executemany(operation,seq_of_params)用于批量操作,如批量更新
fetchone()获取查询结果集中的吓一条记录
fetchmany(size)获取指定数量的记录
fetchall()

获取结果集中的所有记录

nextset()跳到下一个可用的结果集
arraysize指定使用fetchmany获取的行数,默认为1
setinputsize(sizes)设置在调用execute()方法时分配的内存区域大小
setoutputsize(sizes)设置列缓冲区大小,对大数据列(如long和blobs)尤其有用

二、使用SQLite数据库

SQLite是一个数据库文件可以直接操作,体积小,可以直接嵌入到软件中。Python中内置了SQLite3,可以使用import3直接导入SQLite3模块。

 1.创建SQLite数据库文件

使用import直接导入sqlite3模块然后进行数据库操作。

connect()方法参数直接写sqlite文件名即可,若文件不存在时会自动创建数据库文件。

示例:

# _*_ coding:utf-8 _*_


import sqlite3      #导入SQLie3数据库模块


# 创建连接对象
sqlite3conn = sqlite3.connect("demo.db")

# 获取光标对象
cursor = sqlite3conn.cursor()

# 执行sql语句
sql = r"create table if not exists user (id int primary key,name varchar,age int)"

cursor.execute(sql)

# 关闭光标
cursor.close()

# 关闭连接对象
sqlite3conn.close()

结果:

 在统一目录下创建了"demo.db"数据库文件,然后添加了表user

2.操作SQLite

2.1 新增数据

insert into 表名(字段1,字段2,...,字段n) values (字段值1,字段值2,...,字段值n)

使用insert插入数据。

示例:

# _*_ coding:utf-8 _*_


import sqlite3      #导入SQLie3数据库模块


# 创建连接对象
sqlite3conn = sqlite3.connect("demo.db")

# 获取光标对象
cursor = sqlite3conn.cursor()

# 执行sql语句
sql1 = r"insert into user (id, name, age) values (1,'小明',18)"
sql2 = r"insert into user (id, name, age) values (2,'小李',20)"

cursor.execute(sql1)
cursor.execute(sql2)

# 关闭光标
cursor.close()

# 提交事务,将数据变更保存到数据库中。
sqlite3conn.commit()

# 关闭连接对象
sqlite3conn.close()

结果:

成功在标准插入了2条数据。

2.2 查看数据

select * from table where ...
  • fetchone():获取查询结果集的下一条记录
  • fetchmany(size):获取指定数量的记录
  • fetchall():获取所有就
  • 结果集取出的数据会自动从结果集中删除。
  • where可以使用“?”当占位符,然后后面添加元组做判定条件。

示例:

# _*_ coding:utf-8 _*_


import sqlite3      #导入SQLie3数据库模块


# 创建连接对象
sqlite3conn = sqlite3.connect("demo.db")

# 获取光标对象
cursor = sqlite3conn.cursor()

# 执行sql语句
sql = r"select * from user"

cursor.execute(sql)

print("fetchone():{}".format(cursor.fetchone()))
print("fetchmany():{}".format(cursor.fetchmany(2)))
print("fetchall():{}".format(cursor.fetchall()))

# 使用?当占位符,execute语句中用元组替换符号
sql = r"select * from user where id>?"

cursor.execute(sql,(2,))
print("fetchall():{}".format(cursor.fetchall()))

# 关闭光标
cursor.close()

# 提交事务,将数据变更保存到数据库中。
sqlite3conn.commit()

# 关闭连接对象
sqlite3conn.close()

结果:

========================== RESTART: D:\Desktop\Demo.py =========================
fetchone():(1, '小明', 18)
fetchmany():[(2, '小李', 20), (3, '老王', 30)]
fetchall():[(4, '老赵', 40), (5, '小天', 10), (6, '老钱', 70)]
fetchall():[(3, '老王', 30), (4, '老赵', 40), (5, '小天', 10), (6, '老钱', 70)]
>>> 

2.3 修改数据

update table set 字段名=字段值 where 查询条件

示例:

# _*_ coding:utf-8 _*_


import sqlite3      #导入SQLie3数据库模块


# 创建连接对象
sqlite3conn = sqlite3.connect("demo.db")

# 获取光标对象
cursor = sqlite3conn.cursor()

# 执行sql语句
sql = r"update user set name = ? where id = ?"
cursor.execute(sql,("new name",1))

# 关闭光标
cursor.close()

# 提交事务,将数据变更保存到数据库中。
sqlite3conn.commit()

# 关闭连接对象
sqlite3conn.close()

结果:

 2.4 删除数据

delete from table where 查询条件

示例:

# _*_ coding:utf-8 _*_


import sqlite3      #导入SQLie3数据库模块


# 创建连接对象
sqlite3conn = sqlite3.connect("demo.db")

# 获取光标对象
cursor = sqlite3conn.cursor()

# 执行sql语句
sql = r"delete from user where id = ?"
cursor.execute(sql,(1,))
cursor.execute(sql,(4,))

# 关闭光标
cursor.close()

# 提交事务,将数据变更保存到数据库中。
sqlite3conn.commit()

# 关闭连接对象
sqlite3conn.close()

结果:

三、使用MySQL

1.下载安装MySql模块

参考:MySQL 8.0 安装、卸载教程(图文+说明)_鱼听禅的博客-CSDN博客

2.安装PyMySQL

PyMySQL在python的基本库中,可直接在cmd中使用pip指令安装。

pip install PyMySQL
C:\Users\LJM>pip install PyMySQL
Collecting PyMySQL
  Downloading PyMySQL-1.0.2-py3-none-any.whl (43 kB)
     |████████████████████████████████| 43 kB 1.1 MB/s
Installing collected packages: PyMySQL
Successfully installed PyMySQL-1.0.2
WARNING: You are using pip version 20.1.1; however, version 22.3.1 is available.
You should consider upgrading via the 'c:\users\ljm\appdata\local\programs\python\python37\python.exe -m pip install --upgrade pip' command.

C:\Users\LJM>

注意

pip指令如果无效时需要在环境变量中添加pip.exe的目录路径。

3.连接数据库

PyMySQL的connect()信息:

    Connect = class Connection(builtins.object)
     |  Connect(*, user=None, password='', host=None, database=None, unix_socket=None, port=0, charset='', sql_mode=None, read_default_file=None, conv=None, use_unicode=True, client_flag=0, cursorclass=<class 'pymysql.cursors.Cursor'>, init_command=None, connect_timeout=10, read_default_group=None, autocommit=False, local_infile=False, max_allowed_packet=16777216, defer_connect=False, auth_plugin_map=None, read_timeout=None, write_timeout=None, bind_address=None, binary_prefix=False, program_name=None, server_public_key=None, ssl=None, ssl_ca=None, ssl_cert=None, ssl_disabled=None, ssl_key=None, ssl_verify_cert=None, ssl_verify_identity=None, compress=None, named_pipe=None, passwd=None, db=None)
     |  
     |  Representation of a socket with a mysql server.
     |  
     |  The proper way to get an instance of this class is to call
     |  connect().
     |  
     |  Establish a connection to the MySQL database. Accepts several
     |  arguments:
     |  
     |  :param host: Host where the database server is located
     |  :param user: Username to log in as
     |  :param password: Password to use.
     |  :param database: Database to use, None to not use a particular one.
     |  :param port: MySQL port to use, default is usually OK. (default: 3306)
     |  :param bind_address: When the client has multiple network interfaces, specify
     |      the interface from which to connect to the host. Argument can be
     |      a hostname or an IP address.
     |  :param unix_socket: Optionally, you can use a unix socket rather than TCP/IP.
     |  :param read_timeout: The timeout for reading from the connection in seconds (default: None - no timeout)
     |  :param write_timeout: The timeout for writing to the connection in seconds (default: None - no timeout)
     |  :param charset: Charset you want to use.
     |  :param sql_mode: Default SQL_MODE to use.
     |  :param read_default_file:
     |      Specifies  my.cnf file to read these parameters from under the [client] section.
     |  :param conv:
     |      Conversion dictionary to use instead of the default one.
     |      This is used to provide custom marshalling and unmarshalling of types.
     |      See converters.
     |  :param use_unicode:
     |      Whether or not to default to unicode strings.
     |      This option defaults to true.
     |  :param client_flag: Custom flags to send to MySQL. Find potential values in constants.CLIENT.
     |  :param cursorclass: Custom cursor class to use.
     |  :param init_command: Initial SQL statement to run when connection is established.
     |  :param connect_timeout: Timeout before throwing an exception when connecting.
     |      (default: 10, min: 1, max: 31536000)
     |  :param ssl:
     |      A dict of arguments similar to mysql_ssl_set()'s parameters.
     |  :param ssl_ca: Path to the file that contains a PEM-formatted CA certificate
     |  :param ssl_cert: Path to the file that contains a PEM-formatted client certificate
     |  :param ssl_disabled: A boolean value that disables usage of TLS
     |  :param ssl_key: Path to the file that contains a PEM-formatted private key for the client certificate
     |  :param ssl_verify_cert: Set to true to check the validity of server certificates
     |  :param ssl_verify_identity: Set to true to check the server's identity
     |  :param read_default_group: Group to read from in the configuration file.
     |  :param autocommit: Autocommit mode. None means use server default. (default: False)
     |  :param local_infile: Boolean to enable the use of LOAD DATA LOCAL command. (default: False)
     |  :param max_allowed_packet: Max size of packet sent to server in bytes. (default: 16MB)
     |      Only used to limit size of "LOAD LOCAL INFILE" data packet smaller than default (16KB).
     |  :param defer_connect: Don't explicitly connect on construction - wait for connect call.
     |      (default: False)
     |  :param auth_plugin_map: A dict of plugin names to a class that processes that plugin.
     |      The class will take the Connection object as the argument to the constructor.
     |      The class needs an authenticate method taking an authentication packet as
     |      an argument.  For the dialog plugin, a prompt(echo, prompt) method can be used
     |      (if no authenticate method) for returning a string from the user. (experimental)
     |  :param server_public_key: SHA256 authentication plugin public key value. (default: None)
     |  :param binary_prefix: Add _binary prefix on bytes and bytearray. (default: False)
     |  :param compress: Not supported
     |  :param named_pipe: Not supported
     |  :param db: **DEPRECATED** Alias for database.
     |  :param passwd: **DEPRECATED** Alias for password.
     |  
     |  See `Connection <https://www.python.org/dev/peps/pep-0249/#connection-objects>`_ in the
     |  specification.

示例:

# _*_ coding:utf-8 _*_


import pymysql      #导入数据库模块


# 创建连接对象
mysqlconn = pymysql.connect(host = "127.0.0.1",port = 3306 ,user = "root",passwd = "root", database = "demo")

# 获取光标对象
cursor = mysqlconn.cursor()

# 执行sql语句
sql = r"select version()"
cursor.execute(sql)

data = cursor.fetchone()
print("Database Version:{}".format(data))

# 关闭光标
cursor.close()

# 关闭连接对象
mysqlconn.close()
print("Closed database.")

结果:

Database Version:('8.0.18',)
Closed database.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/94730.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

STM32F4 | 定时器中断实验

文章目录一、STM32F429 通用定时器简介二、硬件设计三、软件设计四、实验现象五、STM32CubeMX 配置定时器更新中断功能这一章介绍如何使用 STM32F429 的通用定时器&#xff0c; STM32F429 的定时器功能十分强大&#xff0c;有 TIME1 和 TIME8 等高级定时器&#xff0c;也有 …

从外包到拿下阿里 offer,这 2 年 5 个月 13 天到底发生了什么?

开篇介绍 个人背景&#xff1a; 不说太多废话&#xff0c;但起码要让你先对我有一个基本的了解。本人毕业于浙江某二本院校&#xff0c;算是科班出身&#xff0c;毕业后就进了一家外包公司做开发&#xff0c;当然不是阿里的外包&#xff0c;具体什么公司就不透露了&#xff0…

机器学习100天(一):001 开发环境搭建

机器学习实战需要编写代码,选择一个好的 IDE 能大大提高我们的开发效率。基于 Python 的广泛使用,我们给大家介绍当前最流行的机器学习开发工具包:Anaconda。 一、为什么选择 Anaconda 我们知道 Python 是人工智能的首选语言。为了更好、更方便地使用 Python 来编写机器学…

Linux||后续1:Ubuntu20.04安装MySQL8.0纯命令图文教程(安装+排错+可视化工具+常用命令)

我是碎碎念:) 之前写过一篇用Ubuntu20.04安装MySQL的教程&#xff0c;指路如下 Linux||Ubuntu20.04安装MySQL详细图文教程_Inochigohan的博客-CSDN博客 但方法不是用Linux命令安装的&#xff0c;感觉用着不太顺手&#x1f61c; 索性就重装一遍&#xff0c;纯当是温故而知新好啦…

为什么我们越来越反感「消息通知」?

在日常生活中&#xff0c;我们可以接触到很多「消息通知」&#xff1a; ● 响起门铃声意味着门外有人来访&#xff1b; ● 开车时&#xff0c;仪表盘上显示的发动机温度、行车速度等信息&#xff0c;辅助我们随时了解汽车情况&#xff1b; ● 每当手机电量低于20%时&#xf…

C++ 银行家算法与时间片轮转调度算法结合

一.实验目的 (1) 掌握 RR(时间片调度) 算法&#xff0c;了解 RR 进程调度 (2) 了解死锁概念&#xff0c;理解安全状态&#xff0c;并且理解银行家算法 (3) 利用 RR 进程调度与银行家算法结合&#xff0c;写出一个简单的项目 二.实验原理 2.1 时间片调度算法 在分时系统中都…

SpringBoot整合WebSocket实现简易聊天室

文章目录什么是WebSocket ?WebSocket通信模型为什么需要WebSocketWebsocket与http的关系SpringBoot集成WebSocket什么是WebSocket ? WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单&#xff0c;允许服务端主动…

Opencv(C++)笔记--腐蚀与膨胀操作、创建滑动条

目录 1--膨胀操作 2--腐蚀操作 3--腐蚀和膨胀的作用 4--创建滑动条 5--实例代码 1--膨胀操作 ① 原理&#xff1a; 将图像&#xff08;原图像的一部分 A &#xff09;与核矩阵&#xff08;结构元素 B &#xff09;进行运算&#xff0c;将结构元素 B 覆盖图像 A&#xff0…

[附源码]Nodejs计算机毕业设计基于的数字图书馆系统Express(程序+LW)

该项目含有源码、文档、程序、数据库、配套开发软件、软件安装教程。欢迎交流 项目运行 环境配置&#xff1a; Node.js Vscode Mysql5.7 HBuilderXNavicat11VueExpress。 项目技术&#xff1a; Express框架 Node.js Vue 等等组成&#xff0c;B/S模式 Vscode管理前后端分…

离散被解释变量

一、二值选择模型 采用probit或者logit模型 logit y x1 x2 ,nolog r vce(cluster clustervar) ornolog表示不用显示迭代过程vce(cluster cluster)表示运用聚类标准误&#xff0c;由于二值选择模型一般采用稳健标准误的意义不大&#xff0c;所以常常使用聚类标准误。or 表示结…

数据可视化:对比漏斗图多维度分析大学在校实际开销情况

都说80后90后是“苦逼”的一代&#xff0c;他们读小学的时候&#xff0c;上大学免费&#xff1b;等到他们上大学了&#xff0c;读小学免费。可事实真的是这样吗&#xff1f;下面小编用一款数据可视化软件&#xff0c;带你解读一下现在的大学生&#xff0c;开销到底有多少。 漏…

怎样判断一个变量是数组还是对象?

判断的基本方法 1. typeof(不可以) 通常情况下&#xff0c;我们第一时间会想到typeof运算符&#xff0c;因为typeof是专门用于类型检测的&#xff0c;但是typeof并不能满足这样的需求&#xff0c;比如 let a [7,4,1] console.log(typeof(a)) //输出object 复制代码 2. in…

以太网 VLAN的5种划分方式(基于端口、基于MAC地址、基于IP子网、基于协议、基于策略)介绍与基础配置命令

2.8.3 以太网 VLAN&#xff08;VLAN划分方式&#xff09; VLAN的划分方式有2.8.3 以太网 VLAN&#xff08;VLAN划分方式&#xff09;一、基于端口划分二、基于MAC地址划分三、基于IP子网划分四、基于协议划分五、基于策略划分一、基于端口划分 简述&#xff1a;端口上进行手动…

bitset位图的介绍与使用

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录bitset的介绍位图的引入位图的概念位图的应用bitset的使用bitset的定义方式bitset的成员函数bitset运算符的使用如有错误&#xff0c;多多指教&#xff01;bitset的介…

传奇GEE引擎微端架设教程

传奇GEE引擎微端架设教程 GEE引擎架设微端需要准备好微端程序&#xff0c;用网站下载在服务器的版本 Mirserver文件一般都是自带微端程序的&#xff0c;偶尔也有版本没有微端程序那我们只需要到别的版本或者资源把微端程序拉到我们的文件夹里面D&#xff1a;\Mirserver 这个就…

MyBatisPlus常用注解

MyBatisPlus常用注解 TableName&#xff1a;自定义表名 给User实体类添加注解 aplication.yml中添加mp的配置 # 配置mp的日志 mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl# 设置MyBatis-Plus的全局配置global-config:db-config:table…

java基础巩固-宇宙第一AiYWM:为了维持生计,架构知识+分布式微服务+高并发高可用高性能知识序幕就此拉开(三:注册中心balabala)~整起

比如咱们作为客户端进行购物时&#xff0c;那么多服务提供者【服务提供者有很多实例&#xff0c;可能人家已经搞了拆分模块后的分布式集群&#xff0c;那实例就不少啦】&#xff0c;如果用非技术的眼光看就是&#xff0c;你提供多个&#xff0c;我挑一个买&#xff0c;咱们的访…

立足浙江 辐射全国 护航数字经济发展|美创科技亮相首届数贸会

12月11日-14日&#xff0c;首届全球数字贸易博览会在杭州隆重召开。作为国内唯一经党中央、国务院批准的以数字贸易为主题的国家级、全球性专业博览会&#xff0c;首届数贸会由浙江省人民政府和商务部联合主办&#xff0c;杭州市人民政府、浙江省商务厅和商务部贸发局共同承办。…

EtherCAT设备协议详解二、EtherCAT状态机及配置流程

EtherCAT状态机&#xff08;ESM&#xff09; EtherCAT状态机定义了每个EtherCAT从站设备的分步设置&#xff0c;并指示了可用的功能。设备可以拒绝来自主站的状态请求&#xff0c;并通过错误指示&#xff08;AL 状态寄存器中的错误标志&#xff09;和相关错误代码&#xff08;A…

Linux高级 I/O

目录 一、五种I/O模型 1. 阻塞式I/O 2. 非阻塞式I/O 3. I/O复用&#xff08;多路转接&#xff09; 4. 信号驱动式I/O 5. 异步I/O 二、五种I/O模型的比较 三、I/O复用典型使用在下列网络应用场合 一、五种I/O模型 阻塞式I/O非阻塞式I/OI/O复用&#xff08;多路转接&a…