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)輸出結果如下

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM