python - 如何将 postgresql 字段名输出到字典中,而不仅仅是在 python 中输出列名?
问题描述
我有一个 sql 查询,我想将 postgresql 字段名输出到字典中,而不仅仅是在 python 中输出列名?有谁知道这是怎么做到的吗?非常感谢您的帮助!
'''SELECT c.id, x509_commonName(c.certificate), x509_issuerName(c.certificate), x509_notBefore(c.certificate), x509_notAfter(c.certificate), x509_issuerName(c.certificate), x509_keyAlgorithm(c.certificate), x509_keySize(c.certificate), x509_publicKeyMD5(c.certificate), x509_publicKey(c.certificate), x509_rsaModulus(c.certificate), x509_serialNumber(c.certificate), x509_signatureHashAlgorithm(c.certificate), x509_signatureKeyAlgorithm(c.certificate), x509_subjectName(c.certificate), x509_name(c.certificate), x509_name_print(c.certificate), x509_commonName(c.certificate), x509_subjectKeyIdentifier(c.certificate), x509_extKeyUsages(c.certificate), x509_certPolicies(c.certificate), x509_canIssueCerts(c.certificate), x509_getPathLenConstraint(c.certificate), x509_altNames(c.certificate), x509_altNames_raw(c.certificate), x509_cRLDistributionPoints(c.certificate), x509_authorityInfoAccess(c.certificate), x509_print(c.certificate), x509_anyNamesWithNULs(c.certificate), x509_extensions(c.certificate), x509_tbscert_strip_ct_ext(c.certificate), x509_hasROCAFingerprint(c.certificate)
FROM certificate c, certificate_identity ci WHERE
c.id= ci.certificate_id AND ci.name_type = 'dNSName' AND lower(ci.name_value) =
lower(%s) AND x509_notAfter(c.certificate) > statement_timestamp()''', (domain_name,))
解决方案
就像@mad_ 建议的那样,这应该有效:
您需要先建立连接,然后使用所述连接,您就可以跟随
SQL = '''
SELECT c.id, x509_commonName(c.certificate) as common_name,
x509_issuerName(c.certificate) as issuer_name,
x509_notBefore(c.certificate) as not_before
FROM certificate c, certificate_identity ci
WHERE c.id = ci.certificate_id
AND ci.name_type = 'dNSName'
AND lower(ci.name_value) = lower(%s)
AND x509_notAfter(c.certificate) > statement_timestamp()
'''
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(SQL, (domain_name,))
# This will contain a list [{'id': 1, 'common_name': 'something...', ....}]
your_dict_data = cursor.fetchall()
但是,如果您只是要以某种表格格式显示它,我建议您NamedTupleCursor
改用它。
cursor = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
cursor.execute(SQL, (domain_name,))
for certificate in cursor.fetchall():
print(certificate.id)
print(certificate.common_name)
print(certificate.issuer_name)
我删除了你的很多列,因为浏览所有列并重命名它们会很耗时。所以..我留给你的任务
推荐阅读
- mysql - 如果超出 SQL Server 中指定的长度大小,则将逗号分隔的单行变为多行
- logback - Logback MDC 似乎不适用于自定义类加载器
- r - 使用summary计算后如何找到百分比
- javascript - 如何在javascript中移动数组内的值
- excel - 使用 VBA 中的公式在输出中出错
- android - 使用滑动刷新布局刷新 Firestore 分页适配器中的数据
- c++ - Windows 上的 sf::Music:api-ms-win-crt-locale-l1-1-0.dll:无法打开共享对象文件
- r - 使用 R 和 ggplot 将 y 轴调整为 2x2 ANOVA 条形图的问题
- kubernetes - Kubernetes Native Java 堆栈的含义是什么?
- python - 按 utf-8 的降序按值对 dict 进行排序