236 lines
7.8 KiB
Python
236 lines
7.8 KiB
Python
import psycopg2
|
|
from psycopg2 import sql
|
|
from psycopg2.errors import DuplicateDatabase
|
|
from neo4j import GraphDatabase
|
|
from PyQt5.QtWidgets import QApplication, QMainWindow, QGridLayout, QWidget, QTableWidget, QTableWidgetItem, \
|
|
QHeaderView, QVBoxLayout, QLabel
|
|
from PyQt5.QtCore import QSize, Qt
|
|
|
|
import os
|
|
from dotenv import load_dotenv
|
|
load_dotenv()
|
|
|
|
NEO_USER = os.getenv('NEO_USER')
|
|
NEO_PASS = os.getenv('NEO_PASS')
|
|
NEO_HOST = os.getenv('NEO_HOST')
|
|
|
|
POSTGRES_USER = os.getenv('POSTGRES_USER')
|
|
POSTGRES_DB = os.getenv('POSTGRES_DB')
|
|
POSTGRES_PASS = os.getenv('POSTGRES_PASS')
|
|
POSTGRES_HOST = os.getenv('POSTGRES_HOST')
|
|
POSTGRES_PORT = os.getenv('POSTGRES_PORT')
|
|
|
|
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("postgre") # 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])))
|
|
|
|
|
|
class NeoWindow(QWidget):
|
|
def __init__(self, parent_window):
|
|
super().__init__()
|
|
|
|
self.setWindowTitle("neo4j")
|
|
self.resize(300, 250)
|
|
|
|
grid_layout = QGridLayout(self) # Create QGridLayout
|
|
self.setLayout(grid_layout) # Set this layout in central widget
|
|
|
|
self.table = QTableWidget(self)
|
|
self.table.setColumnCount(1)
|
|
self.table.setRowCount(1)
|
|
|
|
self.table.setHorizontalHeaderLabels(["Info"])
|
|
|
|
# Set the tooltips to headings
|
|
self.table.horizontalHeaderItem(0).setToolTip("Info")
|
|
|
|
# Set the alignment to the headers
|
|
self.table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignHCenter)
|
|
|
|
|
|
grid_layout.addWidget(self.table, 0, 0) # Adding the table to the grid
|
|
|
|
# Position the window to the right of the parent window
|
|
self.position_relative_to_parent(parent_window)
|
|
|
|
def position_relative_to_parent(self, parent_window):
|
|
# Get the geometry of the parent window
|
|
parent_frame = parent_window.frameGeometry()
|
|
|
|
# Calculate new position (right of parent window with a small gap)
|
|
new_x = parent_frame.x() + parent_frame.width() + 5
|
|
new_y = parent_frame.y()
|
|
|
|
# Move the window to the new position
|
|
self.move(new_x, new_y)
|
|
|
|
def load_data(self, neo_data):
|
|
for i, node_data in enumerate(neo_data):
|
|
row_number = self.table.rowCount()-1
|
|
if len(neo_data) != self.table.rowCount():
|
|
self.table.insertRow(row_number)
|
|
self.table.setItem(row_number, 0, QTableWidgetItem(str(node_data[0]["title"])))
|
|
|
|
self.table.resizeColumnsToContents()
|
|
|
|
if __name__ == "__main__":
|
|
import sys
|
|
|
|
conn = psycopg2.connect("user=postgres password=456 host=localhost port=5432")
|
|
|
|
createuUiversityDB(conn)
|
|
|
|
conn = psycopg2.connect("user={0} dbname={1} password={2} host={3} port={4}".format(POSTGRES_USER, POSTGRES_DB,
|
|
POSTGRES_PASS, POSTGRES_HOST, POSTGRES_PORT))
|
|
|
|
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()
|
|
|
|
URI = NEO_HOST
|
|
AUTH = (NEO_USER, NEO_PASS)
|
|
|
|
with GraphDatabase.driver(URI, auth=AUTH) as driver:
|
|
records, summary, keys = driver.execute_query(
|
|
"MATCH (nineties:Movie) WHERE nineties.released >= 1990 AND nineties.released < 2000 RETURN nineties"
|
|
)
|
|
|
|
neo_window = NeoWindow(mw)
|
|
neo_window.load_data(records)
|
|
neo_window.show()
|
|
sys.exit(app.exec()) |