zoukankan      html  css  js  c++  java
  • pymysql 返回数据为字典形式(key:value--列:值)

    一、需求

    在数据库的操作中,有时需要直接返回数据库表中的栏位名称+栏位值的key:value这种字典格式的方法。

    Python DB-API使用流程:

    1. 引入API模块。
    2. 获取与数据库的连接。
    3. 执行SQL语句和存储过程。
    4. 关闭数据库连接。

    二、配置方式

    1.表的内容如下,获取数据要以id:1,name:rui这种形式

    2.程序pymysql连接配置

    1)配置如下

    [dba@wanliu-jx-db-218 monitor]$ cat mysql_m_ccpay.py
    #coding=utf-8
    import pymysql
    import time
     
    class MySQL_Status_Output:
        def __init__(self,host,port,user,password):
            try:
                self.db = pymysql.connect(host=host,port=port,user=user,password=password)
                #self.cursor = self.db.cursor()
                self.cursor = self.db.cursor(cursor = pymysql.cursors.DictCursor)
            except Exception as e:
                print('Wrong')
                print(e)
        def mysql_select_sql(self,sql):
            try:
                self.cursor.execute(sql)
                #col=self.cursor.description
                v_result=self.cursor.fetchall()
                return v_result
            except Exception as e:
                print(e)
        def close(self):
            self.db.close()
     
    if __name__ == "__main__":
        while True:
            time.sleep(3)
            try:
                pro_db = MySQL_Status_Output('127.0.0.1',3306,'dbadmin','dbadmin')
                ccpay_machine_enable= pro_db.mysql_select_sql(" select id '序号',name '姓名',age '年龄' from test.test ")
                pro_db.close()
                print(ccpay_machine_enable)
                for i in range(len(ccpay_machine_enable)):
                    print(ccpay_machine_enable[i])
            except Exception as e:
                print('Is Wrong')
                print(e)
    2)输出结果如下
  • 相关阅读:
    Openmp编程练习
    PAT-1107 Social Clusters (30 分) 并查集模板
    [无需建树]已知前序或后序和中序遍历结果,输出前序或后序或层次遍历的方法汇总
    微机原理与接口技术笔记(二)
    微机原理与接口技术笔记(一)
    win32API多线程编程
    PAT-1021 Deepest Root (25 分) 并查集判断成环和联通+求树的深度
    PAT-1015 Reversible Primes (20 分) 进制转换+质数
    PAT-1022 Digital Library (30 分) 字符串处理
    PAT-1013 Battle Over Cities (25 分) DFS求连通块
  • 原文地址:https://www.cnblogs.com/xibuhaohao/p/9996571.html
Copyright © 2011-2022 走看看