python操作Mysql数据库

目前工作中主要使用的还是mysql数据库,这里把常用的函数做下总结。

python3选择使用pymysql包进行数据库操作,使用pip3 install PyMySQL来进行安装

为了方便查看,这里建一个test数据库,people表进行举例。

1

2

3

4

5

6

7CREATE TABLE `people` ( `name` char(20) DEFAULT NULL,

`age` tinyint(2) DEFAULT NULL,

`weight` float DEFAULT NULL )

ENGINE=InnoDB DEFAULT CHARSET=latin1

#这里将表里插入两条语句

insert into people values("heng","30","170");

insert into people values("de","31","171");

连接数据库

1

2

3

4

5

6

7

8

9

10import pymysql

def connect_local_db():

connect = pymysql.connect(host='localhost',

user='root',

password='root',

db='test',

port=3306,

charset='utf8')

cursor = connect.cursor()

return connect, cursor

这里可以把需要连接的数据库分别写成一个函数,将游标和db传出去,方便调用

查询

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17# 使用 execute() 方法执行 SQL 查询

cursor.execute("select * from people")

# 使用 fetchone() 方法获取单条数据.

data = cursor.fetchone()

#使用 fetchall() 方法获取全部数据.

data = cursor.fetchall()

def test_select():

sql = "select * from people"

cursor.execute(sql)

data = cursor.fetchone()

print("fetchone data is",data)

cursor.execute(sql)

data = cursor.fetchall()

print("fetchall data is",data)

#需要注意的是这里抽取完的data是以元组形式存在的

1

2

3fetchone data is ('heng', 30, 170.0)

fetchall data is (('heng', 30, 170.0), ('de', 31, 171.0))

可以看到fetchone取出的是一个元组,而fetchall取出的是一个元组的列表

插入数据

如果数据量少可以逐条插入,如果数据量多则需要批量插入(先将待插入数据写成元组,然后使用executemany函数进行批量插入)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26def test_select():

sql = "select * from people"

cursor.execute(sql)

data = cursor.fetchall()

print("fetchall data is",data)

#逐条插入

def test_insert1():

sql = 'insert into people values("heng2","32","172")'

cursor.execute(sql)

connect.commit()

test_insert1()

test_select()

## out:fetchall data is (('heng', 30, 170.0), ('de', 31, 171.0), ('heng2', 32, 172.0))

#批量插入

def test_insert2():

sql = 'insert into people (name, age, weight) values(%s,%s,%s)'

insert_data = (("heng3","32","172"),("heng4","32","172"),("heng5","32","172"))

cursor.executemany(sql, insert_data)

connect.commit()

test_insert2()

test_select()

## out:fetchall data is (('heng', 30, 170.0), ('de', 31, 171.0), ('heng2', 32, 172.0),

## ('heng3', 32, 172.0), ('heng4', 32, 172.0), ('heng5', 32, 172.0))

对时间进行插入时,踩过一些坑。

在插入单条时,这里的%s必须带双引号,不然会报错

但是在插入多条时,%s不能加引号,加引号会报错

1

2

3

4

5

6

7

8

9

10

11import datetime

create_time = datetime.datetime.now()

sql = ('insert into people (name, age, weight, create_time) values("heng2","32","172","%s")'%create_time)

# 在插入单条时,这里的%s必须带双引号,不然会报错

# out:fetchall data is ((1, 'heng2', 32, 172.0, datetime.datetime(2020, 12, 11, 18, 5, 32)),)

#但是在插入多条时,%s不能加引号,加引号会报错

sql = 'insert into people (name, age, weight, create_time) values(%s,%s,%s,%s)'

create_time = datetime.datetime.now()

insert_data = (("heng3","32","172",create_time),("heng4","32","172",create_time))

插入文本时需要去除特殊符号,或者进行转义

例如,想插入“!@#$%^&*()/{}[]”,或者包含特殊字符的字符串。如果直接插入会报sql错误。我们需要对%s加单引号(双引号不行),注意这种情况下第一个转义字符会被忽略

1

2

3str_test = '\!@#$%^&*()\/{}[]'

sql = ('insert into people (name, age, weight, create_time) values('%s',"32","172","%s")'%(str_test,create_time))

#out:(6, '!@#$%^&*()/{}[]', 32, 172.0, datetime.datetime(2020, 12, 11, 18, 31, 17))

Rollback的使用

在批量插入时,如果中间报错了, 使用rollback函数会回撤上一条插入,谨慎使用

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16def test_insert2():

sql = 'insert into people (name, age, weight, create_time) values(%s,%s,%s,%s)'

create_time = datetime.datetime.now()

data_all = [[("heng3","32","172",create_time),("heng4","32","172",create_time)],

[("heng3333333333333","32","172",create_time),("heng44444444444444444","32","172",create_time)],

[("heng5","32","172",create_time),("heng6","32","172",create_time)]]

for insert_data in data_all:

try:

cursor.executemany(sql, insert_data)

except Exception as e:

# connect.rollback()

print("error",e)

connect.commit()

test_insert2()

test_select()

#这里第二条插入是超出长度限制的,如果第11行打开则六条记录只能插入最后两条

更新、删除数据

和插入一样,语句执行完成后,使用connect.commit()进行提交,示例如下:

1

2

3

4

5

6

7

8

9

10

11

12

13def test_update():

sql = 'update people set name= "de11", age="22" where id= 1'

cursor.execute(sql)

connect.commit()

test_update()

#id为1的数据被update,这里注意set之后的字段是用逗号分隔的而不是用and

def test_delete():

sql = 'delete from people where id= 1'

cursor.execute(sql)

connect.commit()

test_update()

python mysql latin1_python操作Mysql数据库相关推荐

  1. Python模块MySQLdb操作mysql出现2019错误:Can't initialize character set utf-8

    我使用python的MySQLdb模块实现了一个mysql client, 在测试时,出现了如下错误 Python模块MySQLdb操作mysql出现2019错误:Can't initialize c ...

  2. 数据库MySQL相关操作||创建数据库、显示所有数据库、切换数据库、显示数据库下的数据库表、删除数据库

    数据库MySQL相关操作||创建数据库.显示所有数据库.切换数据库.显示数据库下的数据库表.删除数据库 1,创建数据库 create databases mydb: 记得加:(分号) 2,显示所有数据 ...

  3. mysql常用操作 mysql备份与恢复

    先登录mysql  ==>mysql -uroot -p  查看数据库的版本 select version(); 查看有哪些库 show datases; 查看当前处于哪个库 select da ...

  4. Openstack技术\在Docker容器中部署MySQL,并通过外部mysql客户端操作MySQL Server

    MySQL部署 在Docker容器中部署MySQL,并通过外部mysql客户端操作MySQL Server. 操作步骤: 搜索mysql镜像 拉取mysql镜像 创建容器 操作容器中的mysql 容器 ...

  5. Python FastAPI 框架 操作Mysql数据库 增删改查

    2 比 1 更容易理解,可以先看2(单文件级别) 1.FastAPI 框架 操作Mysql数据库(项目多文件级别) FastAPI 可以使用任何您想要的关系型数据库. 在这里,让我们看一个使用着SQL ...

  6. python启动mysql_Python操作MySQL

    安装PyMySQL python中连接mysql的客户端主要有mysqldb.mysql-connector.pymysql三种.虽说性能上面各有差别,但是主流市场还是以操作便捷.使用简单为选择条件. ...

  7. python豆瓣mysql_python操作mysql

    pymysql:python操作mysql 安装pymysql >: pip3 install pymysql 增删改查 # 选取操作的模块 pymysql # pymysql连接数据库的必要参 ...

  8. python app mysql_Python 操作 MySQL 的5种方式

    不管你是做数据分析,还是网络爬虫,Web 开发.亦或是机器学习,你都离不开要和数据库打交道,而 MySQL 又是最流行的一种数据库,这篇文章介绍 Python 操作 MySQL 的 5 种方式,你可以 ...

  9. 使用python ORM来操作MySQL

    昨天的博客是用MySQL官方的MySQL-connector驱动来完成数据库的连接和使用,但只适用于小项目的操作,当项目规模增加时,代码会越来越复杂,维护成本也越来越高,此时需要一个更好的设计模式.即 ...

最新文章

  1. 像“打游戏”一样用Numpy,试试?
  2. windows 8   远程桌面(RemoteFX )
  3. 前端之同源策略 Jsonp 与 CORS
  4. React 学习之路 (五)事件处理
  5. 电脑如何安装php文件夹在哪个文件夹,win7系统桌面文件在c盘哪个文件夹
  6. python 通过索引迭代列表_Python的索引迭代
  7. 算法习题---线性表之数组实现循环移动
  8. 大数据安全问题的类型有哪些
  9. 厉害了,Netty 轻松实现文件上传!
  10. 诺基亚N8-00测评
  11. Object C中文件后缀名
  12. Java 原生 PCM 格式文件转 WAV
  13. java pptx转图_Java 将PPT转换为图片格式
  14. Python——顺序结构
  15. interface详解
  16. 2020蚂蚁森林自动收能量-保持更新
  17. 第五项修炼-读书笔记
  18. Consul + fabio 实现自动服务发现、负载均衡 1
  19. ChatGPT能够干翻谷歌吗?
  20. 谁说Source Insight只能看C盘的文件?我有妙招!

热门文章

  1. CIO对虚拟化缺乏可预见成最大安全挑战
  2. PageSpeed Insights
  3. Nginx+UWSGI+Django配置全过程
  4. 转如何在Sublime Text 2里增加编辑运行java功能
  5. It's Time to Say Goodbye (此刻告别)
  6. java amr 转 mp3_JAVA 音频转换AMR 转MP3,OS,Linux cent os 7
  7. 服务器购买是有无系统,买服务器含不含操作系统
  8. pycharm 选择变量画图_pycharm画图并显示
  9. 2021年春季学期-信号与系统-第六次作业参考答案-第九小题
  10. 实验室中的机械臂-资料汇总