Base de datos

mail@pastecode.io avatar
unknown
python
a year ago
7.1 kB
1
Indexable
Never
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QLabel, QLineEdit, QTextEdit, QPushButton, QVBoxLayout, QHBoxLayout, QGridLayout, QMessageBox
from PyQt5.QtGui import QFont, QIcon
from PyQt5.QtCore import Qt
import sqlite3


class MovieDatabaseApp(QMainWindow):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("My Movie Database")
        self.setWindowIcon(QIcon("icon.png"))
        self.setGeometry(200, 200, 600, 400)

        self.centralWidget = QWidget(self)
        self.setCentralWidget(self.centralWidget)

        self.titleLabel = QLabel("Título:", self)
        self.titleLabel.setFont(QFont("Arial", 12))

        self.titleLineEdit = QLineEdit(self)
        self.titleLineEdit.setFixedWidth(300)

        self.directorLabel = QLabel("Director:", self)
        self.directorLabel.setFont(QFont("Arial", 12))

        self.directorLineEdit = QLineEdit(self)
        self.directorLineEdit.setFixedWidth(300)

        self.durationLabel = QLabel("Duración (min):", self)
        self.durationLabel.setFont(QFont("Arial", 12))

        self.durationLineEdit = QLineEdit(self)
        self.durationLineEdit.setFixedWidth(100)

        self.genreLabel = QLabel("Género:", self)
        self.genreLabel.setFont(QFont("Arial", 12))

        self.genreLineEdit = QLineEdit(self)
        self.genreLineEdit.setFixedWidth(300)

        self.releaseDateLabel = QLabel("Fecha de estreno (YYYY-MM-DD):", self)
        self.releaseDateLabel.setFont(QFont("Arial", 12))

        self.releaseDateLineEdit = QLineEdit(self)
        self.releaseDateLineEdit.setFixedWidth(150)

        self.ratingLabel = QLabel("Calificación (1-10):", self)
        self.ratingLabel.setFont(QFont("Arial", 12))

        self.ratingLineEdit = QLineEdit(self)
        self.ratingLineEdit.setFixedWidth(100)

        self.countryLabel = QLabel("País de origen:", self)
        self.countryLabel.setFont(QFont("Arial", 12))

        self.countryLineEdit = QLineEdit(self)
        self.countryLineEdit.setFixedWidth(300)

        self.addButton = QPushButton("Agregar", self)
        self.addButton.setFont(QFont("Arial", 12))
        self.addButton.clicked.connect(self.addMovie)

        self.searchLabel = QLabel("Buscar por título, director, género o fecha de estreno:", self)
        self.searchLabel.setFont(QFont("Arial", 12))

        self.searchLineEdit = QLineEdit(self)
        self.searchLineEdit.setFixedWidth(500)
        self.searchLineEdit.textChanged.connect(self.searchMovies)

        self.resultTextEdit = QTextEdit(self)
        self.resultTextEdit.setReadOnly(True)

        self.clearButton = QPushButton("Limpiar", self)
        self.clearButton.setFont(QFont("Arial", 12))
        self.clearButton.clicked.connect(self.clearSearch)

        self.layout = QGridLayout(self.centralWidget)
        self.layout.addWidget(self.titleLabel, 0, 0)
        self.layout.addWidget(self.titleLineEdit, 0, 1)
        self.layout.addWidget(self.directorLabel, 1, 0)
        self.layout.addWidget(self.directorLineEdit, 1, 1)
        self.layout.addWidget(self.durationLabel, 2, 0)
        self.layout.addWidget(self.durationLineEdit, 2, 1)
        self.layout.addWidget(self.genreLabel, 3, 0)
        self.layout.addWidget(self.genreLineEdit, 3, 1)
        self.layout.addWidget(self.releaseDateLineEdit, 4, 1)
        self.layout.addWidget(self.ratingLabel, 5, 0)
        self.layout.addWidget(self.ratingLineEdit, 5, 1)
        self.layout.addWidget(self.countryLabel, 6, 0)
        self.layout.addWidget(self.countryLineEdit, 6, 1)
        self.layout.addWidget(self.addButton, 7, 1)
        self.layout.addWidget(self.searchLabel, 8, 0)
        self.layout.addWidget(self.searchLineEdit, 8, 1)
        self.layout.addWidget(self.resultTextEdit, 9, 0, 1, 2)
        self.layout.addWidget(self.clearButton, 10, 1)

        self.show()

    def addMovie(self):
        title = self.titleLineEdit.text()
        director = self.directorLineEdit.text()
        duration = self.durationLineEdit.text()
        genre = self.genreLineEdit.text()
        release_date = self.releaseDateLineEdit.text()
        rating = self.ratingLineEdit.text()
        country = self.countryLineEdit.text()

        if title == "":
            QMessageBox.warning(self, "Error", "El título no puede estar vacío.")
            return

        conn = sqlite3.connect("movies.db")
        c = conn.cursor()

        try:
            c.execute("""CREATE TABLE IF NOT EXISTS movies (
                            id INTEGER PRIMARY KEY AUTOINCREMENT,
                            title TEXT,
                            director TEXT,
                            duration INTEGER,
                            genre TEXT,
                            release_date TEXT,
                            rating INTEGER,
                            country TEXT
                        )""")
        except Exception as e:
            QMessageBox.critical(self, "Error", "Ocurrió un error al crear la tabla: " + str(e))
            return

        try:
            c.execute("""INSERT INTO movies (title, director, duration, genre, release_date, rating, country)
                            VALUES (?, ?, ?, ?, ?, ?, ?)""",
                      (title, director, duration, genre, release_date, rating, country))
            conn.commit()
            QMessageBox.information(self, "Éxito", "La película se agregó correctamente a la base de datos.")
            self.titleLineEdit.setText("")
            self.directorLineEdit.setText("")
            self.durationLineEdit.setText("")
            self.genreLineEdit.setText("")
            self.releaseDateLineEdit.setText("")
            self.ratingLineEdit.setText("")
            self.countryLineEdit.setText("")
        except Exception as e:
            QMessageBox.critical(self, "Error", "Ocurrió un error al agregar la película: " + str(e))
        finally:
            conn.close()


def searchMovies(self):
    query = self.searchLineEdit.text()

    conn = sqlite3.connect("movies.db")
    c = conn.cursor()

    try:
        c.execute("""SELECT * FROM movies
                        WHERE title LIKE '%' || ? || '%'
                        OR director LIKE '%' || ? || '%'
                        OR genre LIKE '%' || ? || '%'
                        OR release_date LIKE '%' || ? || '%'
                        ORDER BY title""",
                  (query, query, query, query))
        movies = c.fetchall()
        self.resultTextEdit.clear()
        for movie in movies:
            self.resultTextEdit.append("Título: {}\nDirector: {}\nDuración (min): {}\nGénero: {}\nFecha de estreno: {}\nCalificación: {}\nPaís de origen: {}\n\n".format(
                movie[1], movie[2], movie[3], movie[4], movie[5], movie[6], movie[7]))
    except Exception as e:
        QMessageBox.critical(self, "Error", "Ocurrió un error al buscar las películas: " + str(e))
    finally:
        conn.close()

def clearSearch(self):
    self.resultTextEdit.clear()