mysql字典里的key和value_pymysql 返回数据为字典形式(key:value--列:值)

一、需求

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

Python DB-API使用流程:

引入API模块。

获取与数据库的连接。

执行SQL语句和存储过程。

关闭数据库连接。

二、配置方式

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

b2c927e30b183100f318f6328d3b6ddb.png

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)输出结果如下

2ca7f9c18adab80a207b93eb21f07300.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值