• Python之Mysql实战


    欢迎关注【无量测试之道】公众号,回复【领取资源】,
    Python编程学习资源干货、
    Python+Appium框架APP的UI自动化、
    Python+Selenium框架Web的UI自动化、
    Python+Unittest框架API自动化、

    资源和代码 免费送啦~
    文章下方有公众号二维码,可直接微信扫一扫关注即可。

    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-8
    import pymysql
    import dbconfig

    class 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()


    在分享的《Python爬虫之request+beautifulsoup+mysql》文章中会用到本篇文章的内容,请结合着一起阅读。

    备注:我的个人公众号已正式开通,致力于测试技术的分享,包含:大数据测试、功能测试,测试开发,API接口自动化、测试运维、UI自动化测试等,微信搜索公众号:“无量测试之道”,或扫描下方二维码:

     

    添加关注,一起共同成长吧。

  • 相关阅读:
    [bzoj3295][Cqoi2011][动态逆序对] (树套树)
    [bzoj3209][花神的数论题] (数位dp+费马小定理)
    [bzoj1026][SCOI2009][windy数] (数位dp)
    [bzoj4521][Cqoi2016][手机号码] (数位dp+记忆化搜索)
    [bzoj1833][ZJOI2010][count] (数位dp)
    [spoj1182][Sorted Bit Sequence] (数位dp)
    [ural1057][Amount of Degrees] (数位dp+进制模型)
    [hdu3652][B-number] (数位dp)
    【bzoj2523】【CTSC2001】聪明的学生
    友情链接(有的是单向的)
  • 原文地址:https://www.cnblogs.com/Wu13241454771/p/13044176.html
Copyright © 2020-2023  润新知