python操作mysql/mysql增删查改语句
1.2k5WEBpython2018-08-09

PyMySQL安装/方法介绍

PyMySQL是由python编写的,速度上比不上 MySQLdb,但是他安装非常方便同时也兼容 MySQL-python

pip install pymssql

基本方法介绍

close():关闭此connect对象
commit():提交当前事务
rollback():取消当前事务
cursor():创建游标对象

关于游标

游标是一段私有的SQL工作区,也就是一段内存区域,用于暂时存放受SQL语句影响到的数据。通俗理解就是将受影响的数据暂时放到了一个内存区域的虚表中,而这个虚表就是游标。

也就是说在commit之前你操作的都是这个游标,操作错误你可以使用rollback()方法回滚,如果在增删改之后没有commit所有操作都是白搭

操作游标的方法

close():关闭此游标对象
fetchone():得到结果集的下一行
fetchmany([size = cursor.arraysize]):得到结果集的下几行
fetchall():得到结果集中剩下的所有行
excute(sql[, args]):执行一个数据库查询或命令
excutemany(sql, args):执行多个数据库查询或命令

现在上代码

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import pymysql
# 连接mysql
# host为数据库的主机IP地址, port为MySQL的默认端口号, user为数据的用户名, password为数据库的登录密码, db为数据库的名称
config = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': '123456',
'database': 'reptiledata'
}
db = pymysql.connect(**config)
cursor = db.cursor() # 建立游标对象

# -----------------------------------------表操作----------------------------------------------------------------
# 如果存在就删除表
cursor.execute("drop table if exists user")

# 新增表
cursor.execute("""create table if not exists user(
id int auto_increment primary key,
name varchar(5),
sex char(1),
id_card char(18),
phone varchar(14),
address varchar(12),
create_time time)""")

# 修改自增长Id,数据库新增的数据会从1000开始但是原来的数据不会改变
cursor.execute('alter table user AUTO_INCREMENT=1000')

# 新增数据库表字段
cursor.execute('alter table user add plus varchar(8)')
# --------------------------插入数据-------------------------------------------------------------------------------
# 批量插入数据
cursor.execute('alter table user drop plus')

# 插入单条数据但因为后面用了db.rollback()回滚,所以此条数据不会被添加
cursor.execute("""insert into user(name, sex, id_card, phone, address)
values ('李四', '女', '511569845612354879', '10086', '数据不会被添加')""")
db.rollback()

# 批量插入数据,如果不列出字段名mysql会按照顺序添加
sql = """insert into user(name, sex, id_card, phone, address)
values (%s, %s, %s, %s, %s)"""
sql_data = [['张三', '女', '511569845612354879', '10086', '太古里77号'],
['李四', '男', '511569845612354879', '10086', '太古里77号'],
['王麻子子', '男', '511569845612354879', '10086', '太古里66号'],
['张二', '女', '511569845612354879', '10086', '太古里77号'],
['李五', '男', '511569845612354879', '10086', '太古里88号'],
['王麻子', '女', '511569845612354879', '10086', '太古里99号']]
cursor.executemany(sql, sql_data)

# ----------------------------------------查询数据-----------------------------------------------------------------

# order by 对查询结果进行排序 select 字段1,字段2,字段3 from 表名 order by 字段 desc(降序)||asc(升序)
cursor.execute("select address,id from user order by id desc")
select = cursor.fetchall()
print(select)

# 去重复查询 select distinct 字段 from 表名
cursor.execute("select distinct address from user")
select = cursor.fetchall()
print(select)

# 分页查询 limit select 字段1,字段2 from 表名 limit 初始位置,记录数
cursor.execute("select id, name, sex, id_card from user limit 3,6")
select = cursor.fetchall()
print(select)

# 精准查询 in 只查找括号内的数据; not in 则相反
cursor.execute("select * from user where ID in (1001,1003)")
select = cursor.fetchall()
print(select)

# 精准查询 between and 查找1001-1003范围内的数据;not between and 相反
cursor.execute("select * from user where ID between 1001 and 1003")
select = cursor.fetchall()
print(select)

# 模糊查询 like (% 代表任意字符 _ 代表单个字符);not like相反
cursor.execute("select * from user where name like '_麻%'")
select = cursor.fetchall()
print(select)

# 多条件查询 and 关键字
cursor.execute("select * from user where sex='女' and address='太古里77号'")
select = cursor.fetchall()
print(select)

# 多条件查询 or 关键字 只需满足一个条件
cursor.execute("select * from user where name='王麻子子' or address='太古里77号' ")
select = cursor.fetchall()
print(select)

# ------删除数据和更新数据 or,and,between and,like等关键字可以查询到多条数据然后批量删除或者更新-----------------------------------
# 删除数据
cursor.execute("delete from user where name='王麻子子' or address='太古里77号'")
# 数据库清空
cursor.execute("truncate table user")

# 更新数据
cursor.execute("update user set name = '更新' where ID in (1005,1006)")

cursor.close() # 关闭游标对象
db.commit() # 提交操作
db.close() # 关闭数据库

欢迎留言交流  (´▽`ʃ♡ƪ)