# 需要安装的包: pymysql
# 备注:直接下载pymysql可能会下载失败,所以建议使用镜像下载
# 个人在pycharm安装豆瓣、清华、淘宝、阿里云镜像
镜像地址:
清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/
豆瓣:http://pypi.douban.com/simple/
文件配置:
在config文件夹下添加一个conf.py文件,
# 添加配置文件是方便切换测试环境,我们通过切换测试环境实现不同环境的测试
复制代码
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# 存储配置文件 def service_ip(): sit_ip = 'SIT环境连接' uat_ip = 'UST环境连接' return sit_ip # 封装连接串信息 def sql_config(): if service_ip() == 'sit环境连接': host = 'localhost' # 数据库服务器ip地址 username = 'root' # 连接数据库用户名 password = 'root' # 连接数据库密码 port = 8000 # 数据库端口 # 返回连接串信息 return host, username, password, port else: host = 'UAT环境连接' username = 'root' password = 'root' port = 3306 charset = 'utf-8' return host, username, password, port # charset
数据库连接与封装
复制代码
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# 导入包,建立数据库的连接 import pymysql from config.conf import sql_config def get_sql(sql): ''' :param sql:# 运行查询的语句 :return: # 数据库查询结果 ''' # 建立一个连接对象 # user = None, # The first four arguments is based on DB-API 2.0 recommendation. # password = "", # host = None, # database = None, # unix_socket = None, # port = 0, # charset = "", # 定义参数,从cofig配置文件中获取连接串信息 host, username, password, port = sql_config() print(host, username, password, port) # 连接数据库 db = pymysql.connect(host=host, user=username, password=password, port=port) # 建立游标 cursor = db.cursor() print(cursor) # 运行 sql cursor.execute(sql) # 把运行sql的数据保存在data变量里 # 获取查询出的所有值 data = cursor.fetchall() # 将获取的值打印到数组 print(list(data[0])) # 关闭游标 cursor.close() # 关闭连接 db.close() # 返回获取data的数据 return data get_sql('sql查询语句')
最后
以上就是高挑短靴最近收集整理的关于python之mysql数据库连接与封装的全部内容,更多相关python之mysql数据库连接与封装内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复