文章来源:无量测试之道
作者:无量测试之道
Step1、Python 如何操作Mysql?Python通过DB-API,为大多数的数据库实现了接口,使用它连接各数据库后,就可以用相同的方式操作各数据库。
Python DB-API使用流程:
第一步:引入 API 模块。
第二步:获取与数据库的连接。
第三步:执行SQL语句和存储过程。
第四步:关闭数据库连接。
本次是以PyMysql第三方包为示例来分享MySQL数据库的连接,并实现数据库的各种操作。
Step2、如何安装Mysql第三方包?安装命令非常简单:pip install pymysql
Step3、Python 操作Mysql的实例代码是两个文件,一个是配置文件,一个是封装好的操作Mysql文件,代码如下:
dbconfig.py #mysql的配置文件dbDict = {"test5":" beta5.ep.tx1.test.io","test6":"beta6.ep.tx1.test.io","test7":"beta7.ep.tx1.test.io"}dbPort = "3306"dbUser = "tester"dbPassword = "123456"DBUtils.py: #mysql的操作文件#coding:utf-8import pymysqlimport dbconfigclass DBUtils(): def __init__(self,dbtype): print(dbconfig.dbDict.get(dbtype)) self.conn = pymysql.connect(dbconfig.dbDict.get(dbtype), dbconfig.dbUser, dbconfig.dbPassword) self.cursor = self.conn.cursor() def dbSelect(self,sql): print ("------------------------------------") print(sql) resultList = [] self.cursor.execute(sql) result = self.cursor.fetchall() columns = self.cursor.description for val in result: tempDict = {} for cloNum in range(len(columns)): tempDict[str(columns[cloNum][0])] = val[cloNum] resultList.append(tempDict) print("---------------------打印查询结果----------------------") print(resultList) self.dbClose() return resultList def dbExcute(self,sql): print ("execute sql") print(sql) self.cursor.execute(sql) self.dbClose() def dbClose(self): self.conn.commit() self.cursor.close() self.conn.close()
如果你觉得文章不错的话,分享、收藏、在看、留言666是对老表的最大支持。
老表Pro已经满了
所以大家加老表Max吧
近期推荐阅读:
【1】整理了我开始分享学习笔记到现在超过250篇优质文章,涵盖数据分析、爬虫、机器学习等方面,别再说不知道该从哪开始,实战哪里找了【2】【终篇】Pandas中文官方文档:基础用法6(含1-5)
![2fb1ef2a01294d817377272d84173037.png](https://img-blog.csdnimg.cn/img_convert/2fb1ef2a01294d817377272d84173037.png)