相信的心就是你的魔法

pymysql

pymysql在Python中的使用

1
import pymysql

1.和mysql建立连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"""
连接对象 = pymysql.connect(host,port,user,password) - 和指定mysql建立连接并且返回一个连接对象

说明:
host - mysql主机地址(localhost表示当前设备上的mysql, 服务器公网ip)
port - mysql服务端口, 3306
user - mysql用户
password - 用户对应的密码(如果创建用户的时候没有设置密码,这个参数可以不用赋值)
database - 建立连接后默认操作的数据库
charset - 设置连接的数据库文件的编码方式
autocommit - 是否自动提交
"""
con = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='yuting123456',
database='school',
charset='utf8',
autocommit=True
)

2.通过连接获取游标对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
"""
with 连接对象.cursor(查询返回值类型=None) as 游标对象:
数据库操作上下文

说明:
查询返回值类型 - None: 查询结果以元组的形式返回;
pymysql.cursors.DictCursor: 查询结果以字典的形式返回
数据库操作上下文 - 游标对象(数据库操作)只有在数据库操作上下文才有效
"""
with con.cursor() as cursor:
# 数据库操作上下文
# 3.执行sql语句: 游标对象.execute(sql语句)
cursor.execute('create database if not exists pyschool;')

# 关闭连接
con.close()

3.在Python中对表的操作

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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

def query_table(connect):
# 注意: 执行查询的sql语句,查询结果保存在游标对象中的
# 游标对象.fetchall()
sql_str = 'select * from tb_student;'
with connect.cursor(pymysql.cursors.DictCursor) as cursor:
result = cursor.execute(sql_str)
print(result, cursor)

# 注意: cursor中的查询结果,取一个就少一个
# 1. 游标对象.fetchall() - 获取当前查询的所有的结果
# all_result = cursor.fetchall()
# print('查询结果的个数:', len(all_result))
# for dic in all_result:
# print(dic['stuname'])
#
# all_result2 = cursor.fetchall()
# print(all_result2)

# 2. 游标对象.fetchone() - 获取当前查询中一条数据
print(cursor.fetchone())
print(cursor.fetchone())

# 3. 游标对象.fetchmany(size) -- 获取当前查询中指定条数的数据
print(cursor.fetchmany(2))



def operate_table(connect):
"""增删改"""
# 1.增
# sql_str = '''
# insert into tb_student
# (stuname, stusex, stuage, setutel)
# values
# ('张三', 1, 30, '17823736452'),
# ('stu1', 0, 28, '16728729739');
# '''
print('=========插入学生==========')
sql_str = 'insert into tb_student (stuname, stusex, stuage, setutel) values %s;'
str2 = ''
while True:
name = input('请输入名字:')
sex = int(input('请输入性别(0/1):'))
age = int(input('请输入年龄:'))
tel = input('请输入电话号码:')
value = input('是否继续添加(y/n):')
str2 += "('%s', %d, %d, '%s')," % (name, sex, age, tel)

if value == 'n':
print(str2[:-1])
sql_str = sql_str % str2[:-1]
print(sql_str)
break

with connect.cursor() as cursor:
cursor.execute(sql_str)





def create_table(connect):
"""创建表"""
with connect.cursor() as cursor:
# 1.=========创建学生表=========
try:
sql_str = '''
create table tb_student
(
stuid int auto_increment,
stuname varchar(10) not null,
stuage int,
stusex bit default 1,
setutel varchar(11),
primary key (stuid)
);
'''
cursor.execute(sql_str)
except:
pass

# 自定制表
# table_name = input('表名:')
# pre = table_name[:3]
# cnames = []
# while True:
# cname = input('请输入字段名(q-退出):')
# if cname == 'q':
# break
# cnames.append(pre+cname+' text,')
#
# str1 = '''
# create table if not exists tb_%s
# (
# %sid int auto_increment,
# %s
# primary key (%sid)
# );
# '''
#
# sql_str = str1 % (
# table_name,
# table_name[:3],
# ' '.join(cnames),
# table_name[: 3]
# )
# print(sql_str)
# cursor.execute(sql_str)



def main():
# 1.建立连接
con = pymysql.connect(
host='localhost',
user='root',
password='yuting123456',
port=3306,
charset='utf8',
autocommit=True
)

# 2.切换数据库
with con.cursor() as cursor:
cursor.execute('use pyschool;')

# 3.创建表
create_table(con)

# 4.操作表
operate_table(con)

# 5.查询数据
query_table(con)
------ 本文结束------
  • 本文作者: Hanlin Zhang
  • 本文链接: https://hanlin.fun/pymysql/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!