initial commit
This commit is contained in:
commit
6ffbc73964
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
.venv
|
||||
.idea
|
||||
157
main.py
Normal file
157
main.py
Normal file
@ -0,0 +1,157 @@
|
||||
import psycopg2
|
||||
from psycopg2 import sql
|
||||
from psycopg2.errors import DuplicateDatabase
|
||||
from PyQt5.QtWidgets import QApplication, QMainWindow, QGridLayout, QWidget, QTableWidget, QTableWidgetItem, QHeaderView
|
||||
from PyQt5.QtCore import QSize, Qt
|
||||
|
||||
|
||||
def connect(config):
|
||||
""" Connect to the PostgreSQL database server """
|
||||
try:
|
||||
# connecting to the PostgreSQL server
|
||||
with psycopg2.connect(**config) as conn:
|
||||
print('Connected to the PostgreSQL server.')
|
||||
return conn
|
||||
except (psycopg2.DatabaseError, Exception) as error:
|
||||
print(error)
|
||||
|
||||
|
||||
def createUsersDB(config):
|
||||
""" Connect to the PostgreSQL database server """
|
||||
try:
|
||||
# connecting to the PostgreSQL server
|
||||
conn.autocommit = True
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql.SQL("CREATE DATABASE {}").format(
|
||||
sql.Identifier('university'))
|
||||
)
|
||||
print('db created')
|
||||
except DuplicateDatabase:
|
||||
print('db already exists')
|
||||
pass
|
||||
|
||||
|
||||
def createuUiversityDB(config):
|
||||
""" Connect to the PostgreSQL database server """
|
||||
try:
|
||||
# connecting to the PostgreSQL server
|
||||
conn.autocommit = True
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql.SQL("CREATE DATABASE {}").format(
|
||||
sql.Identifier('university'))
|
||||
)
|
||||
print('db created')
|
||||
except DuplicateDatabase:
|
||||
print('db already exists')
|
||||
pass
|
||||
|
||||
|
||||
def createUsersTable(config):
|
||||
""" Connect to the PostgreSQL database server """
|
||||
try:
|
||||
# connecting to the PostgreSQL server
|
||||
conn.autocommit = True
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql.SQL("CREATE TABLE IF NOT EXISTS users(id int, name varchar(255), age int)"))
|
||||
print('table created')
|
||||
except (psycopg2.DatabaseError, Exception) as error:
|
||||
print(error)
|
||||
|
||||
|
||||
def selectUsers(config):
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql.SQL("SELECT * FROM users"))
|
||||
return cur.fetchall()
|
||||
except (psycopg2.DatabaseError, Exception) as error:
|
||||
print(error)
|
||||
return []
|
||||
|
||||
|
||||
def insertUsersData(config, values):
|
||||
""" Connect to the PostgreSQL database server """
|
||||
try:
|
||||
conn.autocommit = True
|
||||
cur = conn.cursor()
|
||||
|
||||
users = selectUsers(conn)
|
||||
|
||||
if len(users) == 0:
|
||||
args = ','.join(cur.mogrify("(%s,%s,%s)", i).decode('utf-8')
|
||||
for i in values)
|
||||
|
||||
# executing the sql statement
|
||||
cur.execute("INSERT INTO users VALUES " + (args))
|
||||
print('inserted')
|
||||
else:
|
||||
print('already inserted')
|
||||
print(users)
|
||||
except (psycopg2.DatabaseError, Exception) as error:
|
||||
print(error)
|
||||
|
||||
|
||||
class MainWindow(QMainWindow):
|
||||
# Override class constructor
|
||||
def __init__(self):
|
||||
# You must call the super class method
|
||||
QMainWindow.__init__(self)
|
||||
|
||||
self.setMinimumSize(QSize(480, 80)) # Set sizes
|
||||
self.setWindowTitle("DB example") # Set the window title
|
||||
central_widget = QWidget(self) # Create a central widget
|
||||
self.setCentralWidget(central_widget) # Install the central widget
|
||||
|
||||
grid_layout = QGridLayout(self) # Create QGridLayout
|
||||
central_widget.setLayout(grid_layout) # Set this layout in central widget
|
||||
|
||||
self.table = QTableWidget(self) # Create a table
|
||||
self.table.setColumnCount(3) # Set three columns
|
||||
self.table.setRowCount(1) # and one row
|
||||
self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
|
||||
# Set the table headers
|
||||
self.table.setHorizontalHeaderLabels(["ID", "Name", "Age"])
|
||||
|
||||
# Set the tooltips to headings
|
||||
self.table.horizontalHeaderItem(0).setToolTip("ID ")
|
||||
self.table.horizontalHeaderItem(1).setToolTip("Name ")
|
||||
self.table.horizontalHeaderItem(2).setToolTip("Age ")
|
||||
|
||||
# Set the alignment to the headers
|
||||
self.table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignHCenter)
|
||||
self.table.horizontalHeaderItem(1).setTextAlignment(Qt.AlignHCenter)
|
||||
self.table.horizontalHeaderItem(2).setTextAlignment(Qt.AlignHCenter)
|
||||
|
||||
# Do the resize of the columns by content
|
||||
self.table.resizeColumnsToContents()
|
||||
|
||||
grid_layout.addWidget(self.table, 0, 0) # Adding the table to the grid
|
||||
|
||||
def load_data(self, users_data):
|
||||
for i, user in enumerate(users_data):
|
||||
row_number = self.table.rowCount()-1
|
||||
if len(users_data) != self.table.rowCount():
|
||||
self.table.insertRow(row_number)
|
||||
self.table.setItem(row_number, 0, QTableWidgetItem(str(user[0])))
|
||||
self.table.setItem(row_number, 1, QTableWidgetItem(str(user[1])))
|
||||
self.table.setItem(row_number, 2, QTableWidgetItem(str(user[2])))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
conn = psycopg2.connect("user=postgres password=456")
|
||||
|
||||
createuUiversityDB(conn)
|
||||
createUsersTable(conn)
|
||||
|
||||
values = [(1, 'Ivan', 15), (2, 'Igor', 22), (3, 'Alex', 16), (4, 'Anna', 40), (5, 'Inna', 30)]
|
||||
|
||||
insertUsersData(conn, values)
|
||||
|
||||
users = selectUsers(conn)
|
||||
|
||||
app = QApplication(sys.argv)
|
||||
mw = MainWindow()
|
||||
mw.load_data(users)
|
||||
mw.show()
|
||||
sys.exit(app.exec())
|
||||
Loading…
Reference in New Issue
Block a user