【问题标题】:How to format postgreSQL queries in a python script for better readability?如何在 python 脚本中格式化 postgreSQL 查询以获得更好的可读性?
【发布时间】:2019-04-13 01:04:58
【问题描述】:

我还有一个与我正在为学校工作的项目有关的问题。我创建了一个 PostgreSQL 数据库,有 5 个表和一堆行。我创建了一个脚本,允许用户使用菜单在数据库中搜索信息,以及在其中一个表中添加和删除内容。

当在 PostgreSQL CLI 本身中显示一个表时,它看起来很干净,但是,即使是在没有用户输入的情况下显示一个简单的表时,它看起来也很混乱。虽然这是该项目的可选组件,但我更希望有一些看起来更干净的东西。

我尝试了各种我在网上看到的潜在解决方案,甚至一些来自堆栈溢出的解决方案,但它们都不起作用。每当我尝试使用我见过并有点理解的任何方法时,我总是会得到错误:

TypeError: 'int' 对象不可下标

我在我的代码中添加了一堆打印语句,试图找出它拒绝类型转换的原因。这是愚蠢的。知道我这可能是一个我看不到的简单错字。甚至不确定这个解决方案是否有效,只是我在网上看到的一个例子。

try:
        connection = psycopg2.connect(database='Blockbuster36', user='dbadmin')
        cursor = connection.cursor()
except psycopg2.DatabaseError:
        print("No connection to database.")
        sys.exit(1)

cursor.execute("select * from Customer;")
tuple = cursor.fetchone()
List_Tuple = list(tuple)

print("Customer_ID | First_Name | Last_Name | Postal_Code | Phone_Num | Member_Date")
print(List_Tuple)
print()
for item in List_Tuple:
        print(item[0]," "*(11-len(str(item[0]))),"|")
        print(item)
        print(type(item))
        print()
        num = str(item[0])
        print(num)
        print(type(num))
        print(str(item[0]))
        print(type(str(item[0])))

cursor.close()
connection.close()

我上传了通过基本 python 脚本和 PostgreSQL CLI 获得的输出之间的差异。出于隐私原因,我已经屏蔽了表格中的姓名。 https://temporysite.weebly.com/

它不必看起来完全像 PostgreSQL,但任何看起来比目前的混乱更好的东西都会很棒。

【问题讨论】:

    标签: python python-3.x formatting psycopg2 postgresql-9.2


    【解决方案1】:

    使用string formatting 来做到这一点。您也可以将其设置为向右或向左填充。 至于日期使用 datetime.strftime。 以下会将填充设置为 10 个位置:

    print(”{:10}|{:10}".format(item[0], item[1]))
    

    【讨论】:

    • 我仍然得到同样的错误:TypeError: 'int' object is not subscriptable
    • 您收到错误是因为您使用的 cursor.fetchone() 仅返回单行作为列表。然后,您尝试遍历列表中的第一个项目,该项目是一个数字。将 cursor.fetchone() 切换到 cursor.fetchall()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 2021-02-09
    • 2021-09-03
    相关资源
    最近更新 更多