问题描述
我试图使用if语句向QTableWidget
从Postgresql中获取数据,但是当我应用变量并分配空值(无)时,表中没有任何显示。而且我不能在QlineEdit
中使用where子句。是否有任何可能的方法可以重现此代码,使其正常工作?
def LoadData(self):
name = self.Name_search.text()
conn = psycopg2.connect(
database = "postgres",user = "postgres",password = "**********",host = "localhost",port = "5432"
)
if name is None:
with conn:
cur = conn.cursor()
rows = cur.execute("Select * from swimming_pool_users where name = '%s'",(name))
data = cur.fetchall()
for row in data:
self.AddTable(row)
cur.close()
def AddTable(self,columns):
rowPosition = self.tableWidget2.rowCount()
self.tableWidget2.insertRow(rowPosition)
for i,column in enumerate(columns):
self.tableWidget2.setItem(rowPosition,i,QtWidgets.QTableWidgetItem(str(column)))
def ClearTableData (self):
while (self.tableWidget2.rowCount() > 0):
self.tableWidget2.removeRow(0)
解决方法
我真的不明白您到底想要什么,但这是一个如何将数据从Postgresql数据库显示到QtableWidgit的示例
def exemple_Qtablewidgit(self):
connection = psycopg2.connect(user="postgres",password="password",host="localhost",database="database")
self.cur = connection.cursor()
name = self.lineEdit.text()
self.cur.execute(''' SELECT * FROM exemple WHERE name =%s''',(name,))
data = self.cur.fetchall()
if data :
self.tableWidget.setRowCount(0)
self.tableWidget.insertRow(0)
for row,form in enumerate(data):
for column,item in enumerate(form):
self.tableWidget.setItem(row,column,QTableWidgetItem(str(item)))
column += 1
row_position = self.tableWidget.rowCount()
self.tableWidget_3.insertRow(row_position)