Вопрос: Как из формы на PyQt5 ввести данные в PostgreSQL 9.4 в Debian 8 (только средствами PyQt5)?
Ответ: при помощи QSqlDatabase и QSqlQuery. Вот пример:
import sys
from PyQt5.QtWidgets import QDialog, QLineEdit, QPushButton, QFormLayout, QApplication
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.fn = QLineEdit()
self.fn.setObjectName("firstname")
self.fn.setText("John")
self.ln = QLineEdit()
self.ln.setObjectName("lastname")
self.ln.setText("Smith")
self.submit = QPushButton()
self.submit.setObjectName("submit")
self.submit.setText("Submit")
layout = QFormLayout()
layout.addWidget(self.fn)
layout.addWidget(self.ln)
layout.addWidget(self.submit)
self.setLayout(layout)
self.submit.clicked.connect(self.button_click)
self.setWindowTitle("Add to PG")
def button_click(self):
fnstring = self.fn.text()
lnstring = self.ln.text()
request = "INSERT INTO table1 (fn,ln) VALUES('" + fnstring + "','" + lnstring + "');"
print request
db = QSqlDatabase.addDatabase("QPSQL")
db.setHostName('localhost')
db.setPort(5432)
db.setDatabaseName('mydb')
db.setUserName('mypguser')
db.setPassword('mypgpassword')
if db.isOpen():
db.close()
if not db.open():
raise Exception("Error opening database: {0}".format(db.lastError().text()))
query = QSqlQuery()
query.exec_(request)
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
Python версии 3.5.2
PyQt5
В 34 строке request взял в скобки
Код выполнился с ошибкой:
INSERT INTO table1 (fn,ln) VALUES(‘John’,’Smith’);
Traceback (most recent call last):
File «/Users/vir2os/PyQt5/BD/BD_postgresql.py», line 103, in button_click
raise Exception(«Error opening database: {0}».format(db.lastError().text()))
Exception: Error opening database: could not connect to server: Connection refused
Is the server running on host «localhost» (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host «localhost» (fe80::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused
Is the server running on host «localhost» (127.0.0.1) and accepting
TCP/IP connections on port 5432?
QPSQL: Unable to connect
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
Добрый день. Судя по всему, ошибка соединения с сервером БД. В чем, собственно, вопрос?
Подскажите как настроить сервер БД, я только недавно начал изучать python)
Разобрался, вопрос закрыт)