python - 如何使用python从postgresql中选择像100这样没有[(100),]的数据?

标签 python python-3.x postgresql

我有一个只有 1 行的表,我只需要更新第一行中的数据。我需要在启动时预览数据,例如总财富:- 2000 现金:- 0 储蓄:- 2000。但预览如下所示。 enter image description here所以请给我一个解决方案。

from tkinter import *
import psycopg2

try:
    connection = psycopg2.connect(user="postgres",
                              password="postgres",
                              host="localhost",
                              port="5432",
                              database="money_db")
    cursor = connection.cursor()

    query_cash = "select cash from main where index = 1;"
    query_savings = "select savings from main where index = 1;"

    cursor.execute(query_cash)
    cash = cursor.fetchall()


    cursor.execute(query_savings)
    savings = cursor.fetchall()


    t_w = (cash + savings)

    cursor.execute("commit;")
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
except (Exception, psycopg2.Error) as error:
    print("Error while fetching data from PostgreSQL", error)

root = Tk()
root.geometry("900x500")
root.resizable(width=False, height=False)

t_w_lbl = Label(text="Total Wealth = " + str(t_w), font=("Calibry", 14), bg="white")
t_w_lbl.place(rely=0.04, relx=0.1)

cash_lbl = Label(text="Cash = " + str(cash), font=("Calibry", 14), bg="white")
cash_lbl.place(rely=0.04, relx=0.45)

photo = PhotoImage(file = "exchange.png")
exchange_btn = Button(image = photo, command = lambda: exchange())
exchange_btn.place(relx = 0.64, rely = 0.03, height = 35, width = 50)

savings_lbl = Label(text="Savings = " + str(savings), font=("Calibry", 14), bg="white")
savings_lbl.place(rely=0.04, relx=0.8)`

最佳答案

您应该使用 fetchone 方法,并解压返回的元组(注意添加的逗号)。

更改:

cash = cursor.fetchall()
...
savings = cursor.fetchall()

至:

cash, = cursor.fetchone()
...
savings, = cursor.fetchone()

关于python - 如何使用python从postgresql中选择像100这样没有[(100),]的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60997164/

相关文章:

python-3.x - Python Tkinter:在放置place()d之后隐藏小部件

sql - PostgreSQL 更新并返回

python - 使用 Pandas 从 Excel 转换为 CSV,我有多个可能的 Excel 工作表名称

python-3.x - Django 上的 MakeMigration 错误 - ImportError : cannot import name 'FieldDoesNotExist' from 'django.db.models'

python - 生成 python 多处理池时意外的内存占用差异

python - Plotly Python 中的刻度格式

postgresql - 如何在所有表中搜索特定值(PostgreSQL)?

linux - 如何在linux上删除postgresql数据库

python - 如何在使用 end ='' 时交替打印 2 个不同的字符串?

python - 在 Mechanize 中获取 '407 Proxy Authentication requires' 错误