pymysql的使用
pymysql是从Python连接到MySQL数据库服务器的接口,其官方文档为:https://pymysql.readthedocs.io/en/latest/
安装:pip install pymysql
对于数据库的操作,我们一般是这样的操作:
步骤1:连接数据库
步骤2:数据库的操作(增删改查)
步骤3:关闭数据库连接
以下是pymysql经常被用到的一些方法
方法 | 描述 |
---|---|
pymysql.connect() | connect()方法返回要给数据库连接对象,参数可以传入很多,常用的参数有:host、port、user、password、database、charset,connect()创建了连接对象,执行完sql操作后,必须使用close()关闭 |
close() | 数据库连接对象的一个方法,用于关闭数据库连接 |
cursor() | 数据库连接对象的一个方法,用于获取游标对象,游标对象的execute(sql语句)方法可以执行sql语句 |
execute(sql) | 游标对象的一个方法,可以执行sql语句 |
commit() | 提交到数据库,数据库连接对象的一个方法,如果对表数据有修改的时候,就需要将修改提交到数据库,否则修改没有生效 |
rollback() | 回滚已提交的内容,,数据库连接对象的一个方法,依据事务的原子性 ,提交要么全部生效,要么全不生效,如果遇到异常,需要对已提交的内容进行回滚 |
数据库连接
方法 | 描述 |
---|---|
pymysql.connect() | connect()方法返回要给数据库连接对象,参数可以传入很多,常用的参数有:host、port、user、password、database、charset,connect()创建了连接对象,执行完sql操作后,必须使用close()关闭 |
close() | 数据库连接对象的一个方法,用于关闭数据库连接 |
- host:mysql服务器地址
- port:mysql服务器连接端口,默认值为3306
- user:用户名
- password:密码
- database:数据库名称
- charset:编码方式,推荐使用"utf8mb4"
简单示例:
import pymysql# 建立连接
conn = pymysql.connect(host="localhost",port=3306,user="root",password="wen",database="mysql",charset="utf8mb4")# 关闭连接
conn.close()
数据库操作
CRUD操作
mysql的操作一般归纳为数据库、表、表数据的增删改查
功能 | 描述 |
---|---|
创建表 | create table 表名 (column_name column_type); |
删除表 | drop table 表名; |
查询表数据 | select 字段名1,字段名2,…,字段名n from 表名 where xxx [limit n][offset m]; |
插入表数据 | insert into 表名(字段名1,字段名2,…,字段名n) values(值1,值2,…,值n),(值21,值22,…,值2n)… ; |
更新表数据 | update 表名 set 字段名1=新值1,字段名2=新值2,…,字段名n=新值n where xxx; |
删除表数据 | delete from 表名 where xxx; |
示例:
import pymysql# 建立连接
conn = pymysql.connect(host="localhost",port=3306,user="root",password="wen",database="test",charset="utf8mb4")
# 执行操作(先获取游标对象,再执行sql语句)
cursor = conn.cursor() # 获取游标对象cursor.execute("show tables;")
print(f"当前test库的表有(创建表前):{cursor.fetchall()}")
# 创建表
creat_table_sql = """create table person(`id` int unsigned auto_increment primary key,`name` varchar(40) not null,`birthday` date);
"""
cursor.execute(creat_table_sql)
cursor.execute("show tables;")
print(f"当前test库的表有(创建表后):{cursor.fetchall()}\n")# 插入表数据
cursor.execute("insert into person(name, birthday) values('wen', '2001-09-23'), ('xiaoba', '1998-04-17');")
conn.commit() # 提交记录# 查询表数据
cursor.execute("select * from person")
print(f"person插入数据后表内容为:{cursor.fetchall()}\n")# 更新表数据
cursor.execute("update person set birthday='2001-12-17' where name='xiaoba';")
conn.commit()
cursor.execute("select * from person")
print(f"person更新数据后表内容为:{cursor.fetchall()}\n")# 删除表数据
cursor.execute("delete from person where name='wen'")
conn.commit()
print(f"person删除数据后表内容为:{cursor.fetchall()}\n")# 关闭连接
conn.close()
执行结果为:
当前test库的表有(创建表前):()
当前test库的表有(创建表后):(('person',),)person插入数据后表内容为:((1, 'wen', datetime.date(2001, 9, 23)), (2, 'xiaoba', datetime.date(1998, 4, 17)))person更新数据后表内容为:((1, 'wen', datetime.date(2001, 9, 23)), (2, 'xiaoba', datetime.date(2001, 12, 17)))person删除数据后表内容为:()
查询操作
游标对象提供了3种获取查询记录的方法
方法 | 描述 |
---|---|
fetchone() | 获取单条记录(元组形式) |
fetchmany(n) | 获取n条记录 (元组形式) |
fetchall() | 获取所有结果记录(元组形式) |
示例:
import pymysql# 建立连接
conn = pymysql.connect(host="localhost",port=3306,user="root",password="wen",database="test",charset="utf8mb4")
# 执行操作(先获取游标对象,再执行sql语句)
cursor = conn.cursor() # 获取游标对象cursor.execute("select * from person where birthday>='2000-01-01'")
result_one = cursor.fetchone()
print(type(result_one))
print(f"fetchone()查询到的内容:{result_one}\n")cursor.execute("select * from person where birthday>='2000-01-01'")
result_3 = cursor.fetchmany(3)
print(type(result_3))
print(f"fetchmany(3)查询到的内容:{result_3}\n")cursor.execute("select * from person where birthday>='2000-01-01'")
result_all = cursor.fetchall()
print(type(result_all))
print(f"fetchall()查询到的内容:{result_all}")# 关闭连接
conn.close()
表内容为:
执行结果为:
<class 'tuple'>
fetchone()查询到的内容:(1, 'wen', datetime.date(2001, 9, 23))<class 'tuple'>
fetchmany(3)查询到的内容:((1, 'wen', datetime.date(2001, 9, 23)), (3, '张三', datetime.date(2012, 7, 9)), (5, 'harry', datetime.date(2013, 7, 9)))<class 'tuple'>
fetchall()查询到的内容:((1, 'wen', datetime.date(2001, 9, 23)), (3, '张三', datetime.date(2012, 7, 9)), (5, 'harry', datetime.date(2013, 7, 9)), (6, 'heng李', datetime.date(2004, 11, 26)))
执行事务
在增加、修改、删除表数据的时候,并不是说实时更新数据库的,当前连接对数据库的操作,要么全做,要么全不做。
pymysql提供了commit()和rollback()这2个方法
功能 | 描述 |
---|---|
commit() | 将游标的所有更新操作进行提交 |
rollback() | 回滚当前游标的所有操作 |
以下是没有执行commit()方法的示例:
import pymysql# 建立连接
conn = pymysql.connect(host="localhost",port=3306,user="root",password="wen",database="test",charset="utf8mb4")
# 执行操作(先获取游标对象,再执行sql语句)
cursor = conn.cursor() # 获取游标对象# 插入表数据
cursor.execute("insert into person(name, birthday) values('harry', '2004-11-23'), ('heng李', '1983-04-28');")# 更新表数据
cursor.execute("update person set birthday='2001-12-17' where name='xiaoba';")# 删除表数据
cursor.execute("delete from person where name='wen'")# 查询表数据
cursor.execute("select * from person")
print(f"person表内容为:{cursor.fetchall()}\n")# 关闭连接
conn.close()
控制台打印结果为:
person表内容为:((2, 'xiaoba', datetime.date(2001, 12, 17)), (3, '张三', datetime.date(2012, 7, 9)), (9, 'harry', datetime.date(2004, 11, 23)), (10, 'heng李', datetime.date(1983, 4, 28)))
test数据库的person表在脚本执行前后如图:
我们看到,在该没有进行commit的脚本中,控制台打印的数据是更新后的数据,但是实际去mysql服务器查询的时候,脚本执行前后,数据并没有变化,可以判断出:游标对象对表数据的修改并没有在表中实际生效。
使用了commit()方法
import pymysql# 建立连接
conn = pymysql.connect(host="localhost",port=3306,user="root",password="wen",database="test",charset="utf8mb4")
# 执行操作(先获取游标对象,再执行sql语句)
cursor = conn.cursor() # 获取游标对象# 插入表数据
cursor.execute("insert into person(name, birthday) values('harry', '2004-11-23'), ('heng李', '1983-04-28');")# 更新表数据
cursor.execute("update person set birthday='2001-12-17' where name='xiaoba';")# 删除表数据
cursor.execute("delete from person where name='wen'")
# 将修改内容提交到数据库
conn.commit()# 查询表数据
cursor.execute("select * from person")
print(f"person表内容为:{cursor.fetchall()}\n")# 关闭连接
conn.close()
执行后:
控制台打印内容为:
person表内容为:((2, 'xiaoba', datetime.date(2001, 12, 17)), (3, '张三', datetime.date(2012, 7, 9)), (11, 'harry', datetime.date(2004, 11, 23)), (12, 'heng李', datetime.date(1983, 4, 28)))
mysql查询:
对比未使用commit()的场景,mysql查询person表的时候,person表内容更新了
rollback()方法一般是用于执行表操作错误后,对已更新的内容进行回滚(如果已经commit()成功的内容,就不回滚,一般来说服,数据库操作均使用try-catch-finally去兼容异常
import pymysqltry:# 建立连接conn = pymysql.connect(host="localhost",port=3306,user="root",password="wen",database="test",charset="utf8mb4")# 执行操作(先获取游标对象,再执行sql语句)cursor = conn.cursor() # 获取游标对象# 更新表数据cursor.execute("update person set birthdaye='2001-12-17' where name='张三';")# 提交修改conn.commit()
except Exception as e:# 回滚事务print(e)print("即将对数据进行回滚")conn.rollback()
finally:# 关闭连接conn.close()
执行结果为:
(1054, "Unknown column 'birthdaye' in 'field list'")
即将对数据进行回滚
pymysql的使用相关推荐
- MySQL之pymysql模块
PyMySQL介绍 PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb. Django中也可以使用PyMySQL连接MySQL数 ...
- MySQL数据库(五)使用pymysql对数据库进行增删改查
折腾好半天的数据库连接,由于之前未安装 pip ,而且自己用的python 版本为3.6. 只能用 pymysql 来连接数据库,(如果有和我一样未安装 pip 的朋友请 点这里http://blog ...
- python使用PyMySQL的连接MySQL数据库
如何实现将100000条数据插入到MySQL数据库?如果使用MySQL客户端来完成这个操作,那么这个工作量无疑是巨大的,可以通过使用程序代码的方式去连接MySQL数据库,然后对MySQL数据库进行增删 ...
- mysql七个模块_mysql(pymysql模块的使用,视图,触发器)
本节重点: pymysql的下载和使用 execute()之sql注入 增.删.改:conn.commit() 查:fetchone.fetchmany.fetchall 一.pymysql的下载和使 ...
- Python 3 —— 使用 PyMySQL 操作 MySQL8
PyMySQL 是一个纯 Python 实现的 MySQL 客户端操作库,支持事务.存储过程.批量执行等. PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Py ...
- sqlalchemy.exc.DataError: (pymysql.err.DataError) (1366, “Incorrect string value: ‘\\xE6问题解决
sqlalchemy.exc.DataError: (pymysql.err.DataError) (1366, "Incorrect string value: '\xE6\xA0\x87 ...
- sqlalchemy.exc.InternalError: (pymysql.err.InternalError) Packet sequence number wrong - got 40 expe
sqlalchemy.exc.InternalError: (pymysql.err.InternalError) Packet sequence number wrong - got 40 expe ...
- pymysql报错:pymysql.err.InterfaceError: (0, '')
在用pymysql时遇到报错: Traceback (most recent call last):File "/usr/local/lib/python3.5/dist-packages/ ...
- python数据库pymysql_Python——数据库04 Python操作MySQL pymysql模块使用,python,04python,MySQLpymysql...
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb. Django中也可以使用PyMySQL连接MySQL数据库. PyMySQ ...
- python pymysql实例_python笔记-mysql命令使用示例(使用pymysql执行)
一.mysql命令使用 学习完mysql现在来进行一些测试 1.1.进入mysql 终端输入一下命令,进入数据库 mysql -uusername -p 1.2 进入数据库 在mysql终端输入如下命 ...
最新文章
- 初学者如何学Java开发
- 通过python+ftps远程备份企业数据
- python if main_python中if __name__ == '__main__' :main(()
- Python3将xml文件解析为Python对象
- python笔记视频_终于拿到!清华大佬Python视频+书+笔记汇总
- 处理字符串_11_判断一个字符是否是数字
- 一个介绍SAP git-enabled CTS的视频
- 2019-03-5-算法-进化(最长公共前缀)
- 第五节:WebApi的三大过滤器
- HDU 2152 Fruit (母函数)
- dsu on tree(Educational Codeforces Round 2: E. Lomsat gelral)
- SQL常用语句(面试必备)
- 维纳(Wiener)滤波及Matlab代码
- C# - 此应用无法在你的电脑上运行
- ZOOM视频会议总是很卡连接不上
- HTML5期末大作业:个人网站设计——简单响应式个人博客HTML模板(8页面) HTML+CSS+JavaScript...
- Asp.net MVC下载文件的四种方法以及下载ZIP文件的一种方法
- 射频day7:微带线;带状线
- 南邮——计算机图像学——会动的立方体(变换)
- 解决在命令行中出现/usr/local/hadoop/libexec/hadoop-functions.sh: 行 1185: dirname: 未找到命令