美文网首页数据分析
python封装数据库

python封装数据库

作者: 吱吱菌啦啦 | 来源:发表于2022-04-18 18:07 被阅读0次

    封装DB,后续对数据库进行操作时,不需要再连一遍

        import pymysql
        def query_db(sql):
            """
            封装DB
            :return:
            """
            # 建立数据库连接
            
            db = pymysql.connect(host="xxx", port=xxx, user="xxx",
                                 password="xxx", database="xxx", charset="utf8")
    
            # 创建游标
            cursor =db.cursor()
            # 使用游标执行sql
            cursor.execute(sql)
            print("行数:", cursor.rowcount)
            datas = cursor.fetchall()
            print("查询到的数据为:", datas)
            cursor.close()
            db.close()
            return datas
    

    以上需替换连接串账号密码等信息~

    调用
    # 导包
    from interface.po.base_api import BaseApi
    
    # 查一条数据测试一下
    def test_search():
        sql = f"SELECT * FROM xxx limit 1"
        dat = BaseApi.query_db(sql)
        print(dat)
    
    image.png

    相关文章

      网友评论

        本文标题:python封装数据库

        本文链接:https://www.haomeiwen.com/subject/lwgdertx.html