解决Python处理sql结果不同类型数据库报错问题:TypeError: tuple indices must be integers or slices, not str

业务场景:

工作中需要通过连接数据库,执行sql,进一步分析sql执行结果,实现业务需求。同样的代码,连接mysql可以,但oracle在执行时报错:TypeError: tuple indices must be integers or slices, not str(类型错误:元组索引必须是整数或切片,而不是字符串。)

问题分析:

代码:

def test_sql():
    """执行sql并写入excel"""
    fp = r"D:\PycharmProjects\Data_statistics\TestData\mysql_num.xlsx"
    datas = HandleExcel(fp, "sql")
    data = datas.read_all_datas()
    for i in data[:2]:
        sql = i["stg_sql"]
        num = db.select_all_data(sql)[0]
        print(num)

分别打印mysql和oracle的sql执行结果,如下:
mysql----sql执行结果为字典:

============= 1 passed in 0.88s =============
Process finished with exit code 0
{'count(*)': 0}
{'count(*)': 0}

oracle----sql执行结果为元组:

============== 1 passed in 6.01s ===============
Process finished with exit code 0
(0,)
(0,)

解决办法:

所以获取sql查询结果时,略有不同
mysql可以读取字典value:num[‘[‘count(*)’]’]
oracle要用索引:num[0]

2023-9-5更新
如果在mysql代码执行过程中,存在多表联查有别名,那么根据字典key读取字典value不太方便,需要根据场景区分,那么建议使用字典方法:(tuple(result.values())[0]) 获取mysql的sql结果

def test_sql():
    """执行sql并写入excel"""
    fp = r"D:\PycharmProjects\Data_statistics\TestData\mysql_num.xlsx"
    datas = HandleExcel(fp, "sql")
    data = datas.read_all_datas()
    for i in data[:1]:
        sql = i["stg_sql"]
        num = db.select_all_data(sql)[0]
        res = (tuple(num.values())[0])
        print(res)

结果:

=============== 1 passed in 2.47s ===============

Process finished with exit code 0
0
PASSED

你可能感兴趣的:(python,数据库,开发语言)