def currentDatabase(self): """ Public method to get the current database. @return reference to the current database (QSqlDatabase) """ return QSqlDatabase.database(self.__activeDb)
def refresh(self): """ Public slot to refresh the connection tree. """ self.__connectionTree.clear() self.cleared.emit() connectionNames = QSqlDatabase.connectionNames() foundActiveDb = False for name in connectionNames: root = QTreeWidgetItem(self.__connectionTree) db = QSqlDatabase.database(name, False) root.setText(0, self.__dbCaption(db)) if name == self.__activeDb: foundActiveDb = True self.__setActive(root) if db.isOpen(): tables = db.tables() for table in tables: itm = QTreeWidgetItem(root) itm.setText(0, table) if not foundActiveDb and connectionNames: self.__activeDb = connectionNames[0] self.__setActive(self.__connectionTree.topLevelItem(0))
def version(): """Return the sqlite version string.""" try: if not QSqlDatabase.database().isOpen(): init(':memory:') ver = Query("select sqlite_version()").run().value() close() return ver return Query("select sqlite_version()").run().value() except SqlError as e: return 'UNAVAILABLE ({})'.format(e)
def version(): """Return the sqlite version string.""" try: if not QSqlDatabase.database().isOpen(): init(':memory:') ver = Query("select sqlite_version()").run().value() close() return ver return Query("select sqlite_version()").run().value() except KnownError as e: return 'UNAVAILABLE ({})'.format(e)
def checkingConnection(self): """This function aims to check the database connection name and use it if exists""" if QSqlDatabase.contains(): self.db = QSqlDatabase.database() self.db.setDatabaseName('database.sqlite') self.db.open() else: self.db = QSqlDatabase.addDatabase("QSQLITE") self.db.setDatabaseName('database.sqlite') self.db.open()
def dveRadyCislovani(self): """ :return: bool """ query = "SELECT 1 FROM doci WHERE druh_cislovani_par = 1" self.setQuery(query, QSqlDatabase.database(self.__mConnectionName)) if self.rowCount() > 0: return True else: return False
def deleteSolution(self): self.solutionsView.setSortingEnabled(False) self.solutionsModel.beginResetModel() index = self.solutionsView.currentIndex() if not index.isValid(): return QSqlDatabase.database().transaction() record = self.solutionsModel.record(index.row()) solution_id = record.value(ID_SOL) point_records = 1 query = QSqlQuery("SELECT COUNT(*) FROM {} " "WHERE id_sol = {}".format(src_pts_tbl_nm, solution_id)) if query.next(): point_records = query.value(0) msg = "<font color=red>Delete record # {}".format(solution_id) if point_records > 1: msg += ", along with {} associated point records".format( point_records) msg += "?</font>" if QMessageBox.question(self, "Delete solution", msg, QMessageBox.Yes | QMessageBox.No) == QMessageBox.No: QSqlDatabase.database().rollback() return query.exec_("DELETE FROM {} WHERE id_sol = {}".format( src_pts_tbl_nm, solution_id)) self.solutionsModel.removeRow(index.row()) self.solutionsModel.submitAll() QSqlDatabase.database().commit() self.solutionsModel.endResetModel() self.solutionsView.setSortingEnabled(True) self.solutionsView.repaint() self.solutionChanged(self.solutionsView.currentIndex())
def __init__(self): #Inicialización de la ventana super().__init__() self.setGeometry(200, 100, 600, 500) self.setMinimumSize(QSize(500, 300)) self.setMaximumSize(QSize(500, 300)) self.setWindowTitle("Gestión de libros") self.setWindowIcon(QIcon("static/icono_CEIC.png")) self.setStyleSheet('background-color: LightSkyBlue') #Base de datos self.db = QSqlDatabase.database('qt_sql_default_connection') self.db.setHostName("localhost") self.db.setDatabaseName("pruebaceic") self.db.setUserName("postgres") self.db.setPassword("postgres") self.db.open() #Creación de fonts para las letras self.titleFont = QFont("Serif", 20) #Título self.title = QLabel("Agregar Autor") self.title.setStyleSheet('color: white') self.title.setFont(self.titleFont) #Aquí vienen los campos self.nombreLabel = QLabel("Nombre del autor") self.nombreInput = QLineEdit(self) self.apellidoLabel = QLabel("Apellido del autor") self.apellidoInput = QLineEdit(self) #CSS self.nombreInput.setStyleSheet('background-color: white') self.apellidoInput.setStyleSheet('background-color: white') #Botones self.agregar = QPushButton("Agregar") self.cancelar = QPushButton("Cancelar") #LAyout self.layout = QVBoxLayout() self.layout.addWidget(self.nombreLabel) self.layout.addWidget(self.nombreInput) self.layout.addWidget(self.apellidoLabel) self.layout.addWidget(self.apellidoInput) self.layout.addWidget(self.agregar) self.layout.addWidget(self.cancelar) self.setLayout(self.layout) self.agregar.clicked.connect(self.anadir) self.cancelar.clicked.connect(self.closeWindow)
def __init__(self, querystr, forward_only=True): """Prepare a new sql query. Args: querystr: String to prepare query from. forward_only: Optimization for queries that will only step forward. Must be false for completion queries. """ super().__init__(QSqlDatabase.database()) log.sql.debug('Preparing SQL query: "{}"'.format(querystr)) if not self.prepare(querystr): raise SqliteError.from_query('prepare', querystr, self.lastError()) self.setForwardOnly(forward_only)
def __init__(self, querystr, forward_only=True): """Prepare a new SQL query. Args: querystr: String to prepare query from. forward_only: Optimization for queries that will only step forward. Must be false for completion queries. """ self.query = QSqlQuery(QSqlDatabase.database()) log.sql.vdebug(f'Preparing: {querystr}') # type: ignore[attr-defined] ok = self.query.prepare(querystr) self._check_ok('prepare', ok) self.query.setForwardOnly(forward_only)
def __init__(self, querystr, forward_only=True): """Prepare a new SQL query. Args: querystr: String to prepare query from. forward_only: Optimization for queries that will only step forward. Must be false for completion queries. """ self.query = QSqlQuery(QSqlDatabase.database()) log.sql.debug('Preparing SQL query: "{}"'.format(querystr)) ok = self.query.prepare(querystr) self._check_ok('prepare', ok) self.query.setForwardOnly(forward_only)
def addAsset(self): row = (self.assetView.currentIndex().row() if self.assetView.currentIndex().isValid() else 0) QSqlDatabase.database().transaction() self.assetModel.insertRow(row) index = self.assetModel.index(row, NAME) self.assetView.setCurrentIndex(index) assetid = 1 query = QSqlQuery() query.exec_("SELECT MAX(id) FROM assets") if query.next(): assetid = query.value(0) query.prepare("INSERT INTO logs (assetid, date, actionid) " "VALUES (:assetid, :date, :actionid)") query.bindValue(":assetid", assetid + 1) query.bindValue(":date", QDate.currentDate()) query.bindValue(":actionid", ACQUIRED) query.exec_() QSqlDatabase.database().commit() #self.logModel.select() self.assetView.edit(index)
def migrate_database(): initial_migration_level = get_migration_level() migration_paths = glob(os.path.join(config.MIGRATIONS_PATH, '*.sql')) for migration in map(lambda p: Migration(p), sorted(migration_paths)): if migration.already_performed(initial_migration_level): continue with open(migration.path, 'r') as f: QSqlDatabase.database().transaction() log_attempting_migration(migration) for statement in f.read().split(';'): query = QSqlQuery() if not query.exec_(statement): fail_migration(query, migration) update_schema_migrations_level(migration) QSqlDatabase.database().commit() log_successful_migration(migration)
def create(self): try: QSqlDatabase.database().transaction() query = QSqlQuery() prepareQuery(query, """ create table clipboardItems( copyTime timestamp, itemHash text, itemText text, itemData blob ); """) executeQuery(query) except ValueError: pass finally: QSqlDatabase.database().commit(); self.setTable('clipboardItems') self.setSort(0, Qt.DescendingOrder) self.select() self.generateRoleNames()
def initdiagUI(self): exitShortcut = QShortcut(QKeySequence('Ctrl+W'), self, qApp.quit) #=====# #=====# #=====# #=====# #=====# #=====# # Create local seperate connection to databse #=====# #=====# #=====# #=====# #=====# #=====# self.db = QSqlDatabase.database("dialog") #=====# #=====# #=====# #=====# #=====# #=====# # Create SqlRecord template with predefined fields #=====# #=====# #=====# #=====# #=====# #=====# self.record_template = QSqlRecord() self.record_template.insert(0, QSqlField('model')) self.record_template.insert(1, QSqlField('order_quantity')) self.record_template.insert(2, QSqlField('order_time')) self.record_template.insert(3, QSqlField('expected_production')) #=====# #=====# #=====# #=====# #=====# #=====# # Main widgets #=====# #=====# #=====# #=====# #=====# #=====# label_model = QLabel('Model', self) label_model.move(40, 50) self.combo = QComboBox(self) self.fillcombo() self.combo.move(180, 50) label_orderquantity = QLabel('Order Quantity', self) label_orderquantity.move(40, 100) self.oq_input = QLineEdit('', self) self.oq_input.move(180, 100) self.error_message = QLabel('', self) self.error_message.move(180, 130) btn_submit = QPushButton('Submit Order', self) btn_submit.move(180, 150) btn_submit.clicked.connect(self.submittodb) self.setFixedSize(350, 200) self.setWindowTitle('Input Dialog') self.show() self.new_record = -1
def insert_batch(self, values, replace=False): """Performantly append multiple rows to the table. Args: values: A dict with a list of values to insert for each field name. replace: If true, overwrite rows with a primary key match. """ q = self._insert_query(values, replace) for key, val in values.items(): q.bindValue(':{}'.format(key), val) db = QSqlDatabase.database() db.transaction() if not q.execBatch(): raise SqliteError.from_query('exec', q.lastQuery(), q.lastError()) db.commit() self.changed.emit()
def try_execute_query_with_qt( query: str) -> Tuple[bool, Union[str, QSqlQuery]]: """ Executes a query in a database using qt tools. :param query: the query to be executed. :type query: string. :return: the success status and the query results. :rtype: a tuple of a boolean and a string or a QSqlQuery instance. """ sqlquery = QSqlQuery(QSqlDatabase.database()) success = sqlquery.exec(query) if success: return True, sqlquery else: return False, "Error with query {}".format(query)
def ok_slot(self, cid, name, dpt): QSqlDatabase.database().transaction() query = QSqlQuery() query.exec( "UPDATE clerks{0} SET clk_id='{1}',clk_name='{2}',dpt_id='{3}'" "WHERE clk_id='{4}'".format(createmoth, cid, name, dpt, self.clk_id)) if 'Yes': QSqlDatabase.database().commit() self.model.select() self.mainModel.select() else: QSqlDatabase.database().rollback()
def veritabaniBaglan(): veritabani = QSqlDatabase.database() if not veritabani.isValid(): veritabani = QSqlDatabase.addDatabase("QSQLITE") if not veritabani.isValid(): logger.error("Veritabanı Eklenemedi !") yaz_dir = QDir() if not yaz_dir.mkpath("."): logger.error("Yazılabilir dizin oluşturulamadı !") # Erişilebilir bir veritabanı dosyası oluşturulmuştur. dosyaAdi = "{}/chat-database.sqlite3".format(yaz_dir.absolutePath()) # Veritabanı mevcut değilse open() fonksiyonu SQLite'ı oluşturacaktır. veritabani.setDatabaseName(dosyaAdi) if not veritabani.open(): logger.error("Veritabanı Açılamadı") QFile.remove(dosyaAdi)
def __init__(self, conname='default', hostname='localhost', port='3306', user='******', password='******'): self.conname = conname self.hostname = hostname if port is '': port = 3306 self.port = int(port) self.user = user self.password = password if (QSqlDatabase.contains(self.conname)): self.db = QSqlDatabase.database(self.conname) else: self.db = QSqlDatabase.addDatabase("QMYSQL", self.conname) self.query = QSqlQuery(self.db)
def setup_results_tableview(self): db_path = self.result_db_path_qle.text() if db_path: success, msg = try_connect_to_sqlite3_db_with_qt(db_path) if not success: QMessageBox.critical(self, self.tool_nm, msg) return pars = parse_db_params(self.db_tables_params) self.solutions_tblnm, self.sol_tbl_flds, self.pts_tbl_nm, self.pts_tbl_flds = pars self.solutionsModel = QSqlTableModel(db=QSqlDatabase.database()) self.solutionsModel.setTable(self.solutions_tblnm) self.solutionsModel.setHeaderData(ID_SOL, Qt.Horizontal, "id") self.solutionsModel.setHeaderData(DIP_DIR, Qt.Horizontal, "dip direction") self.solutionsModel.setHeaderData(DIP_ANG, Qt.Horizontal, "dip angle") self.solutionsModel.setHeaderData(DATASET, Qt.Horizontal, "dataset") self.solutionsModel.setHeaderData(NOTES, Qt.Horizontal, "notes") self.solutionsModel.setHeaderData(SRC_CRS, Qt.Horizontal, "source crs") self.solutionsModel.setHeaderData(CREAT_TIME, Qt.Horizontal, "created") self.solutionsModel.select() self.solutionsView.setModel(self.solutionsModel) self.solutionsView.setSelectionMode(QTableView.MultiSelection) self.solutionsView.setSelectionBehavior(QTableView.SelectRows) self.solutionsView.verticalHeader().hide() self.solutionsView.resizeColumnsToContents() self.solutionsView.resizeRowsToContents() self.solutionsView.setSortingEnabled(True) self.selection_model = self.solutionsView.selectionModel()
def __init__(self): # Inicialización de la ventana super().__init__() self.setWindowTitle("Inventario") self.setWindowIcon(QIcon("static/icono_CEIC.png")) self.setStyleSheet('background-color: rgb(236, 240, 241)') # Base de datos self.db = QSqlDatabase.database('qt_sql_default_connection') self.db.setHostName("localhost") self.db.setDatabaseName("pruebaceic") self.db.setUserName("postgres") self.db.setPassword("postgres") self.db.open() # Creación de fonts para las letras self.titleFont = QFont("Serif", 20) self.titleFont.setBold(True) # Título self.title = QLabel(self) self.title.setText("Inventario") self.title.setStyleSheet('color: rgb(30, 39, 46)') self.title.setFont(self.titleFont) self.title.setGeometry(10, 15, 570, 50) # Línea debajo del título self.line = QtWidgets.QFrame(self) self.line.setGeometry(QtCore.QRect(10, 55, 820, 16)) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") # Tabla donde aparecerán los datos self.table = InventarioBooksTable() # Tablas self.tableLayout = QHBoxLayout() self.tableLayout.addWidget(self.table) self.setLayout(self.tableLayout) self.llenarTabla()
def run_batch(self, values): """Execute the query in batch mode.""" log.sql.debug('Running SQL query (batch): "{}"'.format( self.query.lastQuery())) self._bind_values(values) db = QSqlDatabase.database() ok = db.transaction() self._check_ok('transaction', ok) ok = self.query.execBatch() try: self._check_ok('execBatch', ok) except Error: # Not checking the return value here, as we're failing anyways... db.rollback() raise ok = db.commit() self._check_ok('commit', ok)
def song_delete(self): index = self.ui.tableView_Songs.selectedIndexes() if len(index) > 0: if QMessageBox.question(None, "Confirm delete", "Are you sure to delete '%s' song?" % index[0].sibling(index[0].row(), 1).data(), QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes: assert isinstance(index[0], QModelIndex) row_id = index[0].sibling(index[0].row(), 0).data() db = QSqlDatabase() current_db = db.database() assert isinstance(current_db, QSqlDatabase) current_db.transaction() error_occurred = False error_text = "" song_artist_query = QSqlQuery() song_artist_query.prepare('DELETE FROM t_song_artist WHERE id_song = ' + str(row_id)) if not song_artist_query.exec_(): error_occurred = True error_text = song_artist_query.lastError().text() song_query = QSqlQuery() song_query.prepare('DELETE FROM t_song WHERE id = ' + str(row_id)) if not song_query.exec_(): error_occurred = True error_text = song_query.lastError().text() if not error_occurred: current_db.commit() self.fill_songs_table() else: current_db.rollback() QMessageBox.critical(None, "Database transaction failed", "The database reported an error: %s" % error_text, QMessageBox.Ok)
def addTable(self, database): """ This function creates the table widget, checks the Database connection and run a SQL Query in function of the database name""" self.tableWidget = QTableView() self.tableWidget.setStyleSheet( "font-family: arial; background-color: #F8F8FF;") # Checking connection if QSqlDatabase.contains(): db = QSqlDatabase.database() db.setDatabaseName('database.sqlite') db.open() else: db = QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName('database.sqlite') db.open() # Setting the SQL Query model = QSqlQueryModel() model.setQuery( f'''SELECT id, date, concept, value FROM {database}''', db) # Modeling and setting the Widget Position in the grid self.tableWidget.setModel(model) self.mainLayout.addWidget(self.tableWidget, 5, 0, 1, 3)
def dbToTableView(self, commandSQL): try: QApplication.processEvents() if QSqlDatabase.contains("qt_sql_default_connection"): db = QSqlDatabase.database("qt_sql_default_connection") else: db = QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName(self.dbPath) db.open() projectModel = QSqlQueryModel() projectModel.setQuery(commandSQL, db) projectModel.setHeaderData(0, Qt.Horizontal, 'پلاک') projectModel.setHeaderData(1, Qt.Horizontal, 'بخش') projectModel.setHeaderData(2, Qt.Horizontal, 'تعداد جلد') projectModel.setHeaderData(3, Qt.Horizontal, 'تعداد صفحات') projectModel.setHeaderData(4, Qt.Horizontal, 'نوع') projectModel.setHeaderData(5, Qt.Horizontal, 'همکار تقاضا کننده') projectModel.setHeaderData(6, Qt.Horizontal, 'تحویل گیرنده') projectModel.setHeaderData(7, Qt.Horizontal, 'علت درخواست') projectModel.setHeaderData(8, Qt.Horizontal, 'توضیحات') projectModel.setHeaderData(9, Qt.Horizontal, 'تاریخ تحویل') projectModel.setHeaderData(10, Qt.Horizontal, 'ساعت تحویل') projectModel.setHeaderData(11, Qt.Horizontal, 'تاریخ بازگشت') projectModel.setHeaderData(12, Qt.Horizontal, 'ساعت بازگشت') self.ui.tableView_result.setModel(projectModel) # self.ui.tableView_result.show() self.rowCount = projectModel.rowCount() self.tableResult = projectModel db.close() QApplication.processEvents() except Exception as e: if e.message != '': errormsg = e.message else: errormsg = " " self.errorM('مشکل در ارتباط با دیتابیس\n {}'.format(errormsg))
def deleteAsset(self): index = self.assetView.currentIndex() if not index.isValid(): return QSqlDatabase.database().transaction() record = self.assetModel.record(index.row()) assetid = record.value(ID) logrecords = 1 query = QSqlQuery("SELECT COUNT(*) FROM logs WHERE assetid = {0}".format(assetid)) if query.next(): logrecords = query.value(0) msg = ("<font color=red>Delete</font><br><b>{0}</b>" "<br>from room {1}").format(record.value(NAME),record.value(ROOM)) if logrecords > 1: msg += (", along with {0} log records" .format(logrecords)) msg += "?" if (QMessageBox.question(self, "Delete Asset", msg, QMessageBox.Yes|QMessageBox.No) == QMessageBox.No): QSqlDatabase.database().rollback() return #query.exec_("DELETE FROM logs WHERE assetid = {0}" # .format(assetid)) #use model API self.logModel.setFilter("assetid={0}".format(assetid)) self.logModel.select() if self.logModel.rowCount()>0: self.logModel.removeRows(0,self.logModel.rowCount()) self.logModel.submitAll() self.assetModel.removeRow(index.row()) self.assetModel.submitAll() QSqlDatabase.database().commit() self.assetModel.select() self.assetChanged(self.assetView.currentIndex())
while querySelect.previous(): print(querySelect.value(name), querySelect.value(email)) # print(querySelect.value(name)) # print(querySelect.value(email)) # Create the application's window ''' https://realpython.com/python-pyqt-database/#closing-and-removing-database-connections ''' if con.isOpen(): con.close() # remove database connection # before remove, everything that use connection is deleted # or set to use a different data source print(QSqlDatabase.connectionNames()) QSqlDatabase.removeDatabase(QSqlDatabase.database().connectionName()) print(QSqlDatabase.connectionNames()) win = QLabel("Connection Successfully Opened!") win.setWindowTitle("App Name") win.resize(200, 100) win.show() sys.exit(app.exec_())
def __init__(self): #Inicialización de la ventana super().__init__() self.setWindowTitle("Gestión de estudiantes") self.setWindowIcon(QIcon("static/icono_CEIC.png")) self.setStyleSheet('background-color: rgb(236, 240, 241)') #Base de datos self.db = QSqlDatabase.database('qt_sql_default_connection') self.db.setHostName("localhost") self.db.setDatabaseName("pruebaceic") self.db.setUserName("postgres") self.db.setPassword( "postgres") # RECUERDEN CAMBIAR CONTRASEÑA DEPENDIENDO DE LA SUYA! self.db.open() #Creación de fonts para las letras self.titleFont = QFont("Serif", 20) self.titleFont.setBold(True) self.labelFont = QFont("Helvetica", 13) self.labelFont.setBold(True) self.buttonFont = QFont("Arial", 12) self.buttonFont.setBold(True) # Título self.title = QLabel(self) self.title.setText("Agregar Estudiante") self.title.setStyleSheet('color: rgb(30, 39, 46)') self.title.setFont(self.titleFont) self.title.setGeometry(10, 15, 570, 50) # Línea debajo del título self.line = QtWidgets.QFrame(self) self.line.setGeometry(QtCore.QRect(10, 55, 820, 16)) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") # Line edits para introducir los datos del estudiante self.carnetInput = QLineEdit(self) self.fnameInput = QLineEdit(self) self.lnameInput = QLineEdit(self) self.CIInput = QLineEdit(self) self.phoneInput = QLineEdit(self) self.emailInput = QLineEdit(self) # CSS, PlaceholderText y posicionamiento de los line edits self.carnetInput.setStyleSheet( 'background-color: white; border-radius: 20px; border: 1px solid rgb(210, 218, 226); font: 16px;' ) self.carnetInput.setPlaceholderText(" Carnet del estudiante") self.carnetInput.setGeometry(130, 150, 600, 50) self.fnameInput.setStyleSheet( 'background-color: white; border-radius: 20px; border: 1px solid rgb(210, 218, 226); font: 16px;' ) self.fnameInput.setPlaceholderText(" Nombre del estudiante") self.fnameInput.setGeometry(130, 220, 600, 50) self.lnameInput.setStyleSheet( 'background-color: white; border-radius: 20px; border: 1px solid rgb(210, 218, 226); font: 16px;' ) self.lnameInput.setPlaceholderText(" Apellido del estudiante") self.lnameInput.setGeometry(130, 290, 600, 50) self.CIInput.setStyleSheet( 'background-color: white; border-radius: 20px; border: 1px solid rgb(210, 218, 226); font: 16px;' ) self.CIInput.setPlaceholderText(" Cédula del estudiante") self.CIInput.setGeometry(130, 360, 600, 50) self.phoneInput.setStyleSheet( 'background-color: white; border-radius: 20px; border: 1px solid rgb(210, 218, 226); font: 16px;' ) self.phoneInput.setPlaceholderText(" Teléfono del estudiante") self.phoneInput.setGeometry(130, 430, 600, 50) self.emailInput.setStyleSheet( 'background-color: white; border-radius: 20px; border: 1px solid rgb(210, 218, 226); font: 16px;' ) self.emailInput.setPlaceholderText(" Email del estudiante") self.emailInput.setGeometry(130, 500, 600, 50) #Botones self.agregar = QPushButton(self) self.agregar.setText("Agregar") self.agregar.setFont(self.buttonFont) self.agregar.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.agregar.setGeometry(430, 610, 290, 40) self.cancelar = QPushButton(self) self.cancelar.setText("Cancelar") self.cancelar.setFont(self.buttonFont) self.cancelar.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.cancelar.setGeometry(130, 610, 290, 40) #CSS Botones self.agregar.setStyleSheet("QPushButton:hover\n" "{\n" " background-color: rgb(55, 162, 228);\n" "}\n" "\n" "QPushButton:pressed\n" "{\n" " background-color: rgb(35, 142, 208);\n" "}\n" "QPushButton\n" "{\n" " border-radius: 15px;\n" " background-color: rgb(45, 152, 218);\n" " color: white;\n" "}") self.cancelar.setStyleSheet("QPushButton:hover\n" "{\n" " background-color: #F10000;\n" "}\n" "\n" "QPushButton:pressed\n" "{\n" " background-color: #CC0000;\n" "}\n" "QPushButton\n" "{\n" " border-radius: 15px;\n" " background-color: #C20000;\n" " color: white;\n" "}") #Conexiones de los botones self.agregar.clicked.connect(self.agregarEstudiante) self.cancelar.clicked.connect(self.clean)
def __init__(self): # Inicialización de la ventana super().__init__() self.setWindowTitle("Verificación de Autor") self.setWindowIcon(QIcon("static/icono_CEIC.png")) self.setStyleSheet('background-color: rgb(236, 240, 241)') # Base de datos self.db = QSqlDatabase.database('qt_sql_default_connection') self.db.setHostName("localhost") self.db.setDatabaseName("pruebaceic") self.db.setUserName("postgres") self.db.setPassword("postgres") self.db.open() # Creación de fonts para las letras self.titleFont = QFont("Serif", 20) self.titleFont.setBold(True) self.instruccionFont = QFont("Helvetica", 10) self.instruccionFont.setBold(True) # Título self.title = QLabel(self) self.title.setText("Agregar Libro - Autores") self.title.setStyleSheet('color: rgb(30, 39, 46)') self.title.setFont(self.titleFont) self.title.setGeometry(10, 15, 570, 50) # Línea debajo del título self.line = QtWidgets.QFrame(self) self.line.setGeometry(QtCore.QRect(10, 55, 820, 16)) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") # Instrucción self.instruccion = QLabel(self) self.instruccion.setText("Si alguno de los autores del libro a agregar no \n" \ " aparece en la lista, agréguelo.") self.instruccion.setStyleSheet('color: rgb(79, 90, 94)') self.instruccion.setFont(self.instruccionFont) self.instruccion.setGeometry(525, 240, 300, 50) # Layout para agregar autores self.agregarAutores = QVBoxLayout() self.agregarAutores.addStretch() self.agregar = QPushButton(self) self.agregar.setText("Agregar autor") self.agregar.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.agregar.setGeometry(525, 380, 300, 30) self.agregar.setStyleSheet("QPushButton:hover\n" "{\n" " border-radius: 10px;\n" " background-color: rgb(55, 162, 228);\n" " color: white;\n" "}\n" "\n" "QPushButton:pressed\n" "{\n" " border-radius: 10px;\n" " background-color: rgb(35, 142, 208);\n" " color: white;\n" "}\n" "QPushButton\n" "{\n" " border-radius: 10px;\n" " background-color: rgb(45, 152, 218);\n" " color: white;\n" "}") self.cancelar = QPushButton(self) self.cancelar.setText("Cancelar") self.cancelar.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.cancelar.setGeometry(525, 420, 300, 30) self.cancelar.setStyleSheet("QPushButton:hover\n" "{\n" " border-radius: 10px;\n" " background-color: #C20000;\n" " color: white;\n" "}\n" "\n" "QPushButton:pressed\n" "{\n" " border-radius: 10px;\n" " background-color: #CC0000;\n" " color: white;\n" "}\n" "QPushButton\n" "{\n" " border-radius: 10px;\n" " background-color: #F10000;\n" " color: white;\n" "}") self.seguir = QPushButton(self) self.seguir.setText("Continuar") self.seguir.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.seguir.setGeometry(525, 640, 300, 30) self.seguir.setStyleSheet("QPushButton:hover\n" "{\n" " border-radius: 10px;\n" " background-color: rgb(22, 46, 107);\n" " color: white;\n" "}\n" "\n" "QPushButton:pressed\n" "{\n" " border-radius: 10px;\n" " background-color: rgb(2, 26, 87);\n" " color: white;\n" "}\n" "QPushButton\n" "{\n" " border-radius: 10px;\n" " background-color: rgb(12, 36, 97);\n" " color: white;\n" "}") # Font para los botones self.buttonFont = QFont("Arial", 12) self.buttonFont.setBold(True) self.agregar.setFont(self.buttonFont) self.seguir.setFont(self.buttonFont) self.cancelar.setFont(self.buttonFont) # Widgets para agregar autores self.ingresarNombre = QLineEdit(self) self.ingresarNombre.setStyleSheet( 'background-color: white; border-radius: 10px; border: 1px solid rgb(210, 218, 226);' ) self.ingresarNombre.setPlaceholderText(" Ingrese el nombre del autor") self.ingresarNombre.setGeometry(525, 300, 300, 30) self.ingresarApellido = QLineEdit(self) self.ingresarApellido.setStyleSheet( 'background-color: white; border-radius: 10px; border: 1px solid rgb(210, 218, 226);' ) self.ingresarApellido.setPlaceholderText( " Ingrese el apellido del autor") self.ingresarApellido.setGeometry(525, 340, 300, 30) # Tabla donde aparecerán los datos self.table = autoresTable() #Tablas self.table.llenarAutores() self.widget = QWidget() self.tableLayout = QHBoxLayout() self.tableLayout.addWidget(self.table) self.tableLayout.addWidget(self.widget) # Layout self.layout = QVBoxLayout() self.layout.addStretch() self.layout.addStretch() self.layout.addLayout(self.tableLayout) self.layout.addStretch() self.setLayout(self.layout) # Conexiones de botones self.agregar.clicked.connect(self.anadir) self.cancelar.clicked.connect(self.clean) # Mostrar en pantalla self.instruccion.raise_() self.ingresarNombre.raise_() self.ingresarApellido.raise_() self.agregar.raise_() self.seguir.raise_() self.cancelar.raise_() self.line.raise_()
def song_edit(self): song_id = int(self.ui.label_Songs_Id.text()) song_name = self.ui.lineEdit_Songs_Name.text().strip() artist_count = self.ui.listWidget_Songs_Artist.count() anime = self.ui.comboBox_Songs_Anime.currentText().strip() song_type = self.ui.comboBox_Songs_Type.currentText().strip() song_file = self.ui.lineEdit_Songs_File.text().strip() if song_id != 0: if len(song_name) > 0 and artist_count > 0 and len(anime) > 0 and len(song_type) > 0 and len(song_file) > 0: if QMessageBox.question(None, "Confirm edit", "Are you sure to edit '%d' song id?" % song_id, QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes: db = QSqlDatabase() current_db = db.database() assert isinstance(current_db, QSqlDatabase) current_db.transaction() error_occurred = False error_text = "" artists = self.ui.listWidget_Songs_Artist.findItems("*", Qt.MatchWildcard) artists_id_list = [] for artist in artists: assert isinstance(artist, QListWidgetItem) artist_id, artist_name = artist.text().split(" - ", 1) if int(artist_id) == 0: artist_query = QSqlQuery() artist_query.prepare('INSERT INTO t_artist (name) VALUES (?)') artist_query.bindValue(0, artist_name) if not artist_query.exec_(): error_occurred = True error_text = artist_query.lastError().text() last_id = artist_query.lastInsertId() artists_id_list.append(last_id) else: artists_id_list.append(int(artist_id)) anime_id, anime_name = anime.split(" - ", 1) if int(anime_id) == 0: anime_query = QSqlQuery() anime_query.prepare('INSERT INTO t_anime (name) VALUES (?)') anime_query.bindValue(0, anime_name) if not anime_query.exec_(): error_occurred = True error_text = anime_query.lastError().text() anime_id = anime_query.lastInsertId() else: anime_id = int(anime_id) song_type_id, _ = song_type.split(" - ", 1) song_type_id = int(song_type_id) song_query = QSqlQuery() song_query.prepare('UPDATE t_song SET name = ?, file = ?, id_song_type = ?, id_anime = ? ' 'WHERE id = ?') song_query.bindValue(0, song_name) song_query.bindValue(1, song_file) song_query.bindValue(2, song_type_id) song_query.bindValue(3, anime_id) song_query.bindValue(4, song_id) if not song_query.exec_(): error_occurred = True error_text = song_query.lastError().text() song_artist_now_query = QSqlQuery() song_artist_now_query.prepare('DELETE FROM t_song_artist WHERE id_song = ' + str(song_id)) if not song_artist_now_query.exec_(): error_occurred = True error_text = song_artist_now_query.lastError().text() for artist_insert_id in artists_id_list: song_artist_query = QSqlQuery() song_artist_query.prepare('INSERT INTO t_song_artist (id_song, id_artist) VALUES (?, ?)') song_artist_query.bindValue(0, song_id) song_artist_query.bindValue(1, artist_insert_id) if not song_artist_query.exec_(): error_occurred = True error_text = song_artist_query.lastError().text() if not error_occurred: current_db.commit() self.ui.signals.update_views.emit() else: current_db.rollback() QMessageBox.critical(None, "Database transaction failed", "The database reported an error: %s" % error_text, QMessageBox.Ok) else: QMessageBox.critical(None, "Invalid data", "Fields cannot be empty", QMessageBox.Ok)
def close(): """Close the SQL connection.""" QSqlDatabase.removeDatabase(QSqlDatabase.database().connectionName())
def database(self): return QSqlDatabase.database('media')
def __closeDatabase(self): self.logWidget.logItem("Closing database connection") QSqlDatabase.database().connectionName() self.qDatabaseConnection.close() del self.qDatabaseConnection QSqlDatabase.removeDatabase(QSqlDatabase.database().connectionName())
def __init__(self): # Inicialización de la ventana super().__init__() self.setGeometry(200, 0, 600, 600) self.setWindowTitle("Política de Préstamo") self.setStyleSheet('background-color: rgb(236, 240, 241)') # Base de datos #self.con = psycopg2.connect("dbname=pruebaceic user=postgres host=localhost password=12345 port=5433") #self.cur = self.con.cursor() self.db = QSqlDatabase.database('qt_sql_default_connection') self.db.setHostName("localhost") self.db.setDatabaseName("pruebaceic") self.db.setUserName("postgres") self.db.setPassword("postgres") self.db.open() # Frame para la información de la política de préstamo self.frame_politica = QFrame(self) self.frame_politica.setGeometry(QtCore.QRect(70, 70, 700, 610)) self.frame_politica.setStyleSheet( "background-color: white; border-radius: 10px;") # Font para las letras self.titleFont = QFont("Serif", 20) self.titleFont.setBold(True) self.button_font = QFont("Helvetica", 12) self.button_font.setBold(True) self.text_font = QFont("Helvetica", 10) self.subtitle_font = QFont("Serif", 13) self.subtitle_font.setBold(True) # Título self.title = QtWidgets.QLabel(self) self.title.setText("Política de Préstamo") self.title.setStyleSheet( 'color: #2d3436; background-color: rgba(0, 0, 0, 0);') self.title.setFont(self.titleFont) self.title.setGeometry(280, 100, 300, 30) # Línea debajo del título self.line = QtWidgets.QFrame(self) self.line.setGeometry(QtCore.QRect(190, 140, 450, 5)) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setStyleSheet('border: 40px solid rgb(236, 240, 241)') # Frame para la regla sobre préstamos self.frame_prestamos = QFrame(self) self.frame_prestamos.setGeometry(110, 180, 620, 120) self.frame_prestamos.setStyleSheet( "background-color: #f5f6fa; border-radius: 10px; border: 1px solid #CAD3C8;" ) # Frame para la regla sobre multas self.frame_multas = QFrame(self) self.frame_multas.setGeometry(110, 320, 620, 120) self.frame_multas.setStyleSheet( "background-color: #f5f6fa; border-radius: 10px; border: 1px solid #CAD3C8;" ) # Frame para la regla sobre sanciones self.frame_sanciones = QFrame(self) self.frame_sanciones.setGeometry(110, 460, 620, 120) self.frame_sanciones.setStyleSheet( "background-color: #f5f6fa; border-radius: 10px; border: 1px solid #CAD3C8;" ) # Íconos para la regla de préstamos self.icon_prestamos = QPushButton(self) self.icon_prestamos.setGeometry(120, 190, 100, 100) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("static/préstamos-2790b4.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icon_prestamos.setIcon(icon) self.icon_prestamos.setIconSize(QtCore.QSize(80, 80)) self.icon_prestamos.setFlat(True) self.icon_prestamos.setStyleSheet("background-color: rgba(0,0,0,0)") # Íconos para la regla de multas self.icon_multas = QPushButton(self) self.icon_multas.setGeometry(120, 330, 100, 100) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("static/fines-2790b4.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icon_multas.setIcon(icon) self.icon_multas.setIconSize(QtCore.QSize(90, 90)) self.icon_multas.setFlat(True) self.icon_multas.setStyleSheet("background-color: rgba(0,0,0,0)") # Íconos para la regla de sanciones self.icon_sanciones = QPushButton(self) self.icon_sanciones.setGeometry(120, 470, 100, 100) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("static/banned-2790b4.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.icon_sanciones.setIcon(icon) self.icon_sanciones.setIconSize(QtCore.QSize(90, 90)) self.icon_sanciones.setFlat(True) self.icon_sanciones.setStyleSheet("background-color: rgba(0,0,0,0)") # Subtítulo para la regla de préstamos self.title_prestamos = QLabel(self) self.title_prestamos.setGeometry(230, 190, 200, 20) self.title_prestamos.setFont(self.subtitle_font) self.title_prestamos.setAutoFillBackground(True) self.title_prestamos.setStyleSheet( "color: #2d3436; background-color: rgba(0,0,0,0);") self.title_prestamos.setText("Préstamos") # Subtítulo para la regla de multas self.title_multas = QLabel(self) self.title_multas.setGeometry(230, 330, 200, 20) self.title_multas.setFont(self.subtitle_font) self.title_multas.setAutoFillBackground(True) self.title_multas.setStyleSheet( "color: #2d3436; background-color: rgba(0,0,0,0);") self.title_multas.setText("Multas") # Subtítulo para la regla de sanciones self.title_sanciones = QLabel(self) self.title_sanciones.setGeometry(230, 470, 200, 20) self.title_sanciones.setFont(self.subtitle_font) self.title_sanciones.setAutoFillBackground(True) self.title_sanciones.setStyleSheet( "color: #2d3436; background-color: rgba(0,0,0,0);") self.title_sanciones.setText("Sanciones") # Label para la regla de préstamos self.rule_prestamos = QLabel(self) self.rule_prestamos.setGeometry(230, 210, 490, 80) self.rule_prestamos.setStyleSheet("background-color: rgba(0,0,0,0)") self.rule_prestamos.setWordWrap(True) self.rule_prestamos.setFont(self.text_font) self.rule_prestamos.setAlignment(Qt.AlignLeft) # Label para la regla de multas self.rule_multas = QLabel(self) self.rule_multas.setGeometry(230, 350, 490, 80) self.rule_multas.setStyleSheet("background-color: rgba(0,0,0,0)") self.rule_multas.setWordWrap(True) self.rule_multas.setFont(self.text_font) self.rule_multas.setAlignment(Qt.AlignLeft) # Label para la regla de sanciones self.rule_sanciones = QLabel(self) self.rule_sanciones.setGeometry(230, 490, 490, 80) self.rule_sanciones.setStyleSheet("background-color: rgba(0,0,0,0)") self.rule_sanciones.setWordWrap(True) self.rule_sanciones.setFont(self.text_font) self.rule_sanciones.setAlignment(Qt.AlignLeft) # Colocamos las reglas almacenadas en la base de datos en los labels self.mostrar_politica() # Botón para modificar la política de préstamos self.modificar = QPushButton(self) self.modificar.setGeometry(110, 615, 300, 40) self.modificar.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.modificar.setFont(self.button_font) self.modificar.setText("Modificar") self.modificar.setStyleSheet( "QPushButton:hover\n" "{\n" " background-color: #2790b4;" "}\n" "QPushButton:pressed\n" "{\n" " background-color: #319bbe;" "}\n" "QPushButton\n" "{\n" " color: white;" " border-radius: 20px;" " background-color: qlineargradient(spread:pad, x1:0, \ y1:0, x2:1, y2:0, stop:0 rgba(39, 144, 180, 255), stop:1 rgba(26, 22, 102, 255));" "}") # Botón para cerrar la política de préstamos self.entendido = QPushButton(self) self.entendido.setGeometry(430, 615, 300, 40) self.entendido.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.entendido.setFont(self.button_font) self.entendido.setText("Entendido") self.entendido.setStyleSheet( "QPushButton:hover\n" "{\n" " background-color: #2790b4;" "}\n" "QPushButton:pressed\n" "{\n" " background-color: #319bbe;" "}\n" "QPushButton\n" "{\n" " color: white;" " border-radius: 20px;" " background-color: qlineargradient(spread:pad, x1:0, \ y1:0, x2:1, y2:0, stop:0 rgba(39, 144, 180, 255), stop:1 rgba(26, 22, 102, 255));" "}") # Botón para guardar las modificaciones self.guardar = QPushButton(self) self.guardar.setGeometry(430, 615, 300, 40) self.guardar.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.guardar.setFont(self.button_font) self.guardar.setText("Guardar") self.guardar.setStyleSheet("QPushButton:hover\n" "{\n" " background-color: #2790b4;" "}\n" "QPushButton:pressed\n" "{\n" " background-color: #319bbe;" "}\n" "QPushButton\n" "{\n" " color: white;" " border-radius: 20px;" " background-color: #1d87aa;" "}") # Botón para cancelar las modificaciones self.cancelar = QPushButton(self) self.cancelar.setGeometry(110, 615, 300, 40) self.cancelar.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.cancelar.setFont(self.button_font) self.cancelar.setText("Cancelar") self.cancelar.setStyleSheet("QPushButton:hover\n" "{\n" " background-color: #C20000;" "}\n" "QPushButton:pressed\n" "{\n" " background-color: #CC0000;" "}\n" "QPushButton\n" "{\n" " color: white;" " border-radius: 20px;" " background-color: #F10000;" "}") # Line edits para modificar las reglas de la política de préstamo self.modificar_prestamos = QTextEdit(self) self.modificar_prestamos.setGeometry(220, 180, 510, 120) self.modificar_prestamos.setStyleSheet( "background-color: white; border: 1px solid #CAD3C8;") self.modificar_prestamos.setFont(self.text_font) self.modificar_prestamos.setText(self.prestamos_text) self.modificar_multas = QTextEdit(self) self.modificar_multas.setGeometry(220, 320, 510, 120) self.modificar_multas.setStyleSheet( "background-color: white; border: 1px solid #CAD3C8;") self.modificar_multas.setFont(self.text_font) self.modificar_multas.setText(self.multas_text) self.modificar_sanciones = QTextEdit(self) self.modificar_sanciones.setGeometry(220, 460, 510, 120) self.modificar_sanciones.setStyleSheet( "background-color: white; border: 1px solid #CAD3C8;") self.modificar_sanciones.setFont(self.text_font) self.modificar_sanciones.setText(self.sanciones_text) # Escondemos los line edits self.modificar_prestamos.hide() self.modificar_multas.hide() self.modificar_sanciones.hide() self.guardar.hide() self.cancelar.hide() # Conexiones de los botones self.modificar.clicked.connect(self.modificar_politica) self.guardar.clicked.connect(self.guardar_politica) self.cancelar.clicked.connect(self.cancelar_modificacion)
def __init__(self, databasePath, logWidget): super().__init__() # Log self.logWidget = logWidget # Style # self.setStyleSheet(open('Styles.css').read()) # Comment out if not using custom CSS. # Database self.qDatabaseConnection = None # To allow checking for existing connection to close. self.qDatabaseConnection = self.__openDatabase(databasePath) print(QSqlDatabase.database().connectionName()) # General self.setWindowTitle("whoop") self.errorLabel = QLabel() # TODO remove self.statusBarWidget = StatusBarWidget(self) self.statusBarWidget.showTextMessage("Status: Connected to " + databasePath) # Toolbars self.viewToolBar = ViewToolBar(self) self.modeToolBar = ModeToolBar(self) # TODO abstract? self.generationToolBar = GenerationToolBar(self) self.addToolBar(Qt.TopToolBarArea, self.viewToolBar) self.viewToolBar.setVisible( False) # TODO depricated for now - add for training screen maybe self.settingsToolBar = SettingsToolBar() self.addToolBar(Qt.RightToolBarArea, self.settingsToolBar) # Widgets self.playerWidget = MediaPlayerWidget() self.surveyWidget = SurveyTableWidget() self.stampWidget = StampTableWidget() self.extractorWidget = ExtractorWidget() self.processWidget = ProcessWidget() self.validateWidget = ValidateWidget() self.visualizerWidget = VisualizerWidget() # self.logWidget = logWidget # Docks self.playerDock = QDockWidget("Audio", self) self.surveyDock = QDockWidget("Surveys", self) self.stampDock = QDockWidget("Annotation", self) self.extractorDock = QDockWidget("Extraction", self) self.processDock = QDockWidget("Processing", self) self.validateDock = QDockWidget("Validation", self) self.visualizerDock = QDockWidget("Visualization", self) self.logDock = QDockWidget("Log", self) self.playerDock.setWidget(self.playerWidget) self.surveyDock.setWidget(self.surveyWidget) self.stampDock.setWidget(self.stampWidget) self.extractorDock.setWidget(self.extractorWidget) self.processDock.setWidget(self.processWidget) self.validateDock.setWidget(self.validateWidget) self.visualizerDock.setWidget(self.visualizerWidget) self.logDock.setWidget(self.logWidget) # Screens self.generationScreen = MainScreenSetting(self) # TODO depricated - not using separate screens anymore (just showing docks) since side toolbar can be shared self.processScreen = SeparateScreenSetting(self) # Model/Processing self.kerasModel = None self.worker = ProcessWorker.null() self.modelWorker = ModelWorker.null() self.killProcessingEvent = threading.Event() # extraction self.extractionWorker = ExtractionWorker.null() self.__createInitialView() # signals self.__connectSignals()
def song_add(self): song_name = self.ui.lineEdit_Songs_Name.text().strip() artist_count = self.ui.listWidget_Songs_Artist.count() anime = self.ui.comboBox_Songs_Anime.currentText().strip() song_type = self.ui.comboBox_Songs_Type.currentText().strip() song_file = self.ui.lineEdit_Songs_File.text().strip() if len(song_name) > 0 and artist_count > 0 and len(anime) > 0 and len(song_type) > 0 and len(song_file) > 0: db = QSqlDatabase() current_db = db.database() assert isinstance(current_db, QSqlDatabase) current_db.transaction() error_occurred = False error_text = "" artists = self.ui.listWidget_Songs_Artist.findItems("*", Qt.MatchWildcard) artists_id_list = [] for artist in artists: assert isinstance(artist, QListWidgetItem) artist_id, artist_name = artist.text().split(" - ", 1) if int(artist_id) == 0: artist_query = QSqlQuery() artist_query.prepare('INSERT INTO t_artist (name) VALUES (?)') artist_query.bindValue(0, artist_name) if not artist_query.exec_(): error_occurred = True error_text = artist_query.lastError().text() last_id = artist_query.lastInsertId() artists_id_list.append(last_id) else: artists_id_list.append(int(artist_id)) anime_id, anime_name = anime.split(" - ", 1) if int(anime_id) == 0: anime_query = QSqlQuery() anime_query.prepare('INSERT INTO t_anime (name) VALUES (?)') anime_query.bindValue(0, anime_name) if not anime_query.exec_(): error_occurred = True error_text = anime_query.lastError().text() anime_id = anime_query.lastInsertId() else: anime_id = int(anime_id) song_type_id, _ = song_type.split(" - ", 1) song_type_id = int(song_type_id) song_query = QSqlQuery() song_query.prepare('INSERT INTO t_song (name, file, id_song_type, id_anime) VALUES (?, ?, ?, ?)') song_query.bindValue(0, song_name) song_query.bindValue(1, song_file) song_query.bindValue(2, song_type_id) song_query.bindValue(3, anime_id) if not song_query.exec_(): error_occurred = True error_text = song_query.lastError().text() song_id = song_query.lastInsertId() for artist_insert_id in artists_id_list: song_artist_query = QSqlQuery() song_artist_query.prepare('INSERT INTO t_song_artist (id_song, id_artist) VALUES (?, ?)') song_artist_query.bindValue(0, song_id) song_artist_query.bindValue(1, artist_insert_id) if not song_artist_query.exec_(): error_occurred = True error_text = song_artist_query.lastError().text() if not error_occurred: current_db.commit() self.ui.signals.update_views.emit() self.ui.tableView_Songs.sortByColumn(0, Qt.DescendingOrder) self.ui.label_Songs_Id.setText(str(song_id)) else: current_db.rollback() QMessageBox.critical(None, "Database transaction failed", "The database reported an error: %s" % error_text, QMessageBox.Ok) else: QMessageBox.critical(None, "Invalid data", "Fields cannot be empty", QMessageBox.Ok)