Python 链接数据库 query后的table heads 表格表头/列名 域名 Domain怎么显示

通过cursor.description 可以获得表头。
先cursor.execute(query), 之后再cursor.description

import cx_Oracle as oracle
import pandas as pd

db = oracle.connect('tenant01/[email protected]:1521/orcl')
# 换成自己的db数据
# tenant01是username
# 123456 是密码
# at 后面是ip
# 1521是端口
# orcl是service name
#链接数据库 具体怎么连接请查看

query = "select * from most_viewed_sample m inner join user_profile u on m.userid = u.userid"
 #换成自己的
try:
    cursor = db.cursor()
    cursor.execute(query)
    data = cursor.fetchall()

# 通过cursor.description 获取表头
    SqlDomain = cursor.description
    DomainNum = len(SqlDomain)
    SqlDomainName = [None]*DomainNum
    for i in range(DomainNum):
        SqlDomainName[i] = SqlDomain[i][0]


    df = pd.DataFrame(data)
    df.columns = SqlDomainName



    display(df)
    cursor.close()
    
except:
    print("Query failed")

你可能感兴趣的:(数据库)