Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

from PyQt6 import QtCore, QtGui, QtWidgets import pyodbc def connect(): connstr =…

  1. User

    from PyQt6 import QtCore, QtGui, QtWidgets import pyodbc

    def connect(): conn_str = 'DRIVER={SQL Server};SERVER=SAVITAR\SQLEXPRESS01;DATABASE=kayit;Trusted_Connection=yes;' connection = pyodbc.connect(conn_str) return connection

    class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(616, 779) font = QtGui.QFont() font.setBold(True) font.setItalic(False) font.setUnderline(False) font.setWeight(75) font.setStrikeOut(False) MainWindow.setFont(font) self.centralwidget = QtWidgets.QWidget(parent=MainWindow) self.centralwidget.setObjectName("centralwidget") self.lineEdit = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit.setGeometry(QtCore.QRect(160, 60, 251, 31)) self.lineEdit.setText("") self.lineEdit.setObjectName("lineEdit") self.pushButton = QtWidgets.QPushButton(parent=self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(420, 160, 91, 81)) self.pushButton.setObjectName("pushButton") self.label = QtWidgets.QLabel(parent=self.centralwidget) self.label.setGeometry(QtCore.QRect(0, 60, 121, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) self.label.setFont(font) self.label.setAutoFillBackground(False) self.label.setTextFormat(QtCore.Qt.TextFormat.AutoText) self.label.setWordWrap(False) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(parent=self.centralwidget) self.label_2.setGeometry(QtCore.QRect(0, 100, 121, 51)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) self.label_2.setFont(font) self.label_2.setObjectName("label_2") self.lineEdit_2 = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit_2.setGeometry(QtCore.QRect(160, 110, 251, 31)) self.lineEdit_2.setText("") self.lineEdit_2.setObjectName("lineEdit_2") self.label_3 = QtWidgets.QLabel(parent=self.centralwidget) self.label_3.setGeometry(QtCore.QRect(0, 150, 121, 51)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) self.label_3.setFont(font) self.label_3.setObjectName("label_3") self.lineEdit_3 = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit_3.setGeometry(QtCore.QRect(160, 160, 251, 31)) self.lineEdit_3.setText("") self.lineEdit_3.setObjectName("lineEdit_3") self.label_4 = QtWidgets.QLabel(parent=self.centralwidget) self.label_4.setGeometry(QtCore.QRect(0, 210, 151, 31)) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(12) self.label_4.setFont(font) self.label_4.setAutoFillBackground(False) self.label_4.setTextFormat(QtCore.Qt.TextFormat.AutoText) self.label_4.setWordWrap(False) self.label_4.setObjectName("label_4") self.lineEdit_4 = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit_4.setGeometry(QtCore.QRect(160, 210, 251, 31)) self.lineEdit_4.setText("") self.lineEdit_4.setObjectName("lineEdit_4") self.pushButton_2 = QtWidgets.QPushButton(parent=self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(420, 60, 91, 81)) self.pushButton_2.setObjectName("pushButton_2") self.pushButton_2.clicked.connect(self.ekle) self.pushButton_3 = QtWidgets.QPushButton(parent=self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(520, 60, 91, 81)) self.pushButton_3.setObjectName("pushButton_3") self.pushButton_3.clicked.connect(self.sil) self.pushButton_4 = QtWidgets.QPushButton(parent=self.centralwidget) self.pushButton_4.setGeometry(QtCore.QRect(520, 160, 91, 81)) self.pushButton_4.setObjectName("pushButton_4") self.tableWidget = QtWidgets.QTableWidget(parent=self.centralwidget) self.tableWidget.setGeometry(QtCore.QRect(0, 270, 611, 481)) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setColumnCount(0) self.tableWidget.setRowCount(0) MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar(parent=MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) try: # Veritabanına bağlantı oluşturma connection = connect() # Bağlantı üzerinden bir cursor (imleç) oluşturma cursor = connection.cursor() # SQL sorgusuyla tablodan verileri alma cursor.execute("SELECT ad, id, sehir, sektor FROM Musteriler") data = cursor.fetchall() # Veritabanı bağlantısını ve cursoru kapatma cursor.close() connection.close() # Tabloya verileri ekleme self.tableWidget.setRowCount(len(data)) self.tableWidget.setColumnCount(4 if len(data)==0 else len(data[0])) # Kolon sayısını verilere göre ayarla for row_num, row_data in enumerate(data): for col_num, col_data in enumerate(row_data): item = QtWidgets.QTableWidgetItem(str(col_data)) self.tableWidget.setItem(row_num, col_num, item) # Tablo başlıkları header_labels = ["Müşteri Adı", "Müşteri No", "Şehir", "Sektor"] self.tableWidget.setHorizontalHeaderLabels(header_labels) except pyodbc.Error as error: print("Hata:", error)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "GÜNCELLE"))
        self.label.setText(_translate("MainWindow", "MUSTERİ ADI:"))
        self.label_2.setText(_translate("MainWindow", "MÜŞTERİ NO:"))
        self.label_3.setText(_translate("MainWindow", "ŞEHİR:"))
        self.label_4.setText(_translate("MainWindow", "MÜŞTERİ SEKTÖR:"))
        self.pushButton_2.setText(_translate("MainWindow", "EKLE"))
        self.pushButton_3.setText(_translate("MainWindow", "SİL"))
        self.pushButton_4.setText(_translate("MainWindow", "GÖRÜNTÜLE"))
    
    
    def tabloyu_guncelle(self):
        try:
            connection = connect()
    
            # Tablo widget’ını temizle
            self.tableWidget.clearContents()
            self.tableWidget.setRowCount(0)
    
            # Veritabanından verileri getir
            with connection:
                cursor = connection.cursor()
                cursor.execute("SELECT ad, id, sehir, sektor FROM Musteriler")
                data = cursor.fetchall()
    
            # Tablo widget’ını yeni verilerle güncelle
            self.tableWidget.setRowCount(len(data))
            self.tableWidget.setColumnCount(4 if len(data)==0 else len(data[0]))
            for row_num, row_data in enumerate(data):
                for col_num, col_data in enumerate(row_data):
                    item = QtWidgets.QTableWidgetItem(str(col_data))
                    self.tableWidget.setItem(row_num, col_num, item)
    
        except pyodbc.Error as error:
            print("Hata:", error)
    
    
    
    
    
    def ekle(self):
        try:
            connection = connect()
            musteri_adi = self.lineEdit.text()
            musteri_no = self.lineEdit_2.text()
            sehir = self.lineEdit_3.text()
            musteri_sektor = self.lineEdit_4.text()
            # Veritabanına bağlantı oluşturma ve with bloğu içinde bağlantıyı kullanma
            with connection:
                # Bağlantı üzerinden bir cursor oluşturma
                cursor = connection.cursor()
                # Müşteri verilerini eklemek için INSERT INTO sorgusu
                query = "INSERT INTO Musteriler (ad, id, sehir, sektor) VALUES (?, ?, ?, ?)"
                cursor.execute(query, (musteri_adi, musteri_no, sehir, musteri_sektor))
                # Değişiklikleri kaydetme ve işlemi tamamlama
                connection.commit()
                print("Müşteri başarıyla eklendi.")
            # Yeni müşteri ekledikten sonra tabloya verileri ekleme kısmı
            self.tabloyu_guncelle()
            # Bağlantıyı kapatma
            connection.close()
        except pyodbc.Error as error:
            print("Hata:", error)
    def sil(self):
         try:
            # Bağlantıyı al
            connection = connect()
            
            selected_items = self.tableWidget.selectedItems()
            if selected_items:
                selected_row = selected_items[0].row()
                musteri_no = self.tableWidget.item(selected_row, 1).text()
    
                with connection:
                    cursor = connection.cursor()
                    query = "DELETE FROM Musteriler WHERE id = ?"
                    cursor.execute(query, (musteri_no,))
                    connection.commit()
                    print(f"Seçilen satırın müşteri numarası {musteri_no} olan veri başarıyla silindi.")
                    self.tableWidget.removeRow(selected_row)
            
            # Tablo Güncelleme
            self.tabloyu_guncelle()
         except pyodbc.Error as error:
            print("Hata:", error)
    

    if name == "main": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec())

  2. Assistant

    The given code is a PyQt6 application for managing customer records in a database. Here is a breakdown of the code:

    1. The connect() function is defined to establish a connection with the SQL Server database.

    2. The Ui_MainWindow class is defined, which contains the GUI components and functionality of the application.

    3. The setupUi() method is responsible for setting up the user interface of the main window. It creates and configures the various GUI components such as labels, text fields, buttons, and a table widget.

    4. The retranslateUi() method is used to set the labels and button text to their respective translations.

    5. The tabloyu_guncelle() method is responsible for updating the table widget with the latest data from the database. It retrieves the data using a SQL query and populates the table widget accordingly.

    6. The ekle() method is called when the "EKLE" button is clicked. It retrieves the data entered by the user in the text fields and inserts it into the database using an SQL query.

    7. The sil() method is called when the "SİL" button is clicked. It deletes the selected row(s) from the table widget and the corresponding data from the database using an SQL query.

    8. The if __name__ == "__main__": block is responsible for creating the application, main window, and the Ui_MainWindow instance. It then calls the setupUi() method to set up the UI and starts the event loop with app.exec().

    Note: The pyodbc library is used to connect to the SQL Server database and execute SQL queries. Make sure to install the library before running the code.

  3. User

    self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) try: # Veritabanına bağlantı oluşturma connection = connect() # Bağlantı üzerinden bir cursor (imleç) oluşturma cursor = connection.cursor() # SQL sorgusuyla tablodan verileri alma cursor.execute("SELECT ad, id, sehir, sektor FROM Musteriler") data = cursor.fetchall() # Veritabanı bağlantısını ve cursoru kapatma cursor.close() connection.close() # Tabloya verileri ekleme self.tableWidget.setRowCount(len(data)) self.tableWidget.setColumnCount(4 if len(data)==0 else len(data[0])) # Kolon sayısını verilere göre ayarla for row_num, row_data in enumerate(data): for col_num, col_data in enumerate(row_data): item = QtWidgets.QTableWidgetItem(str(col_data)) self.tableWidget.setItem(row_num, col_num, item) # Tablo başlıkları header_labels = ["Müşteri Adı", "Müşteri No", "Şehir", "Sektor"] self.tableWidget.setHorizontalHeaderLabels(header_labels) except pyodbc.Error as error: print("Hata:", error) peki bu kısımda da tabloyu guncelle fonksiyonuyla düzenleme yapabilir miyiz

  4. Assistant

    Evet, bu kısımda da tabloyu_guncelle() fonksiyonunu kullanarak kodu düzenleyebilirsiniz. Şu şekilde düzenleyebilirsiniz:

    self.tabloyu_guncelle()
    

    Bu satırı try bloğunun sonunda, cursor.close() ve connection.close() satırlarının hemen öncesine eklemeniz gerekir. Böylece veritabanından verileri çeken kod bloğu tamamlandıktan sonra tabloyu güncelleyebilirsiniz.

    İşte bu kısım nasıl görünebilir:

    # Veritabanı bağlantısını ve cursoru kapatma
    cursor.close()
    connection.close()
    
    # Tabloyu güncelle
    self.tabloyu_guncelle()
    
    # Tablo başlıkları
    header_labels = ["Müşteri Adı", "Müşteri No", "Şehir", "Sektor"]
    self.tableWidget.setHorizontalHeaderLabels(header_labels)
    

    Bunu yaptıktan sonra, veritabanından verileri çekip tabloyu güncellemek için tabloyu_guncelle() fonksiyonunu kullanabilirsiniz.

  5. User

    Müşteri no benzersiz olsun istiyorum kullanıcı aynı nolu bir kayıt yapmak istediğinde pop out ile hata mesajı vermeliyim

  6. Assistant

    Müşteri numarasının benzersiz olması için kayıt ekleme işlemi yapmadan önce müşteri numarasının veritabanında mevcut olup olmadığını kontrol etmelisiniz. Eğer müşteri numarası zaten mevcut ise kullanıcıya bir hata mesajı göstermelisiniz.

    İşte ekle() metodunu güncelleyerek bu kontrolü yapabilirsiniz:

    def ekle(self):
        try:
            connection = connect()
            musteri_adi = self.lineEdit.text()
            musteri_no = self.lineEdit_2.text()
            sehir = self.lineEdit_3.text()
            musteri_sektor = self.lineEdit_4.text()
            
            # Müşteri numarasının veritabanında mevcut olup olmadığını kontrol et
            with connection:
                cursor = connection.cursor()
                cursor.execute("SELECT COUNT(*) FROM Musteriler WHERE id = ?", (musteri_no,))
                result = cursor.fetchone()
                if result and result[0] > 0:  # Müşteri numarası mevcut ise hata mesajı göster
                    QtWidgets.QMessageBox.critical(self.centralwidget, "Hata", "Böyle bir müşteri numarası zaten mevcut. Lütfen farklı bir müşteri numarası girin.")
                    return
                
                # Müşteri verilerini eklemek için INSERT INTO sorgusu
                query = "INSERT INTO Musteriler (ad, id, sehir, sektor) VALUES (?, ?, ?, ?)"
                cursor.execute(query, (musteri_adi, musteri_no, sehir, musteri_sektor))
                # Değişiklikleri kaydetme ve işlemi tamamlama
                connection.commit()
                print("Müşteri başarıyla eklendi.")
            
            # Yeni müşteri ekledikten sonra tabloya verileri ekleme kısmı
            self.tabloyu_guncelle()
            # Bağlantıyı kapatma
            connection.close()
        except pyodbc.Error as error:
            print("Hata:", error)
    

    Bu şekilde, müşteri numarasının benzersiz olmasını kontrol edebilir ve kullanıcıya hata mesajı vererek kayıt işlemini engelleyebilirsiniz.

  7. User

    güncelle butonuna fonksiyon eklemek istiyorum

  8. Assistant

    Güncelleme işlemini gerçekleştirmek için "GÜNCELLE" butonuna bir fonksiyon ekleyebilirsiniz. İşte guncelle() adında bir fonksiyon ekleyerek yapabileceğiniz adımlar:

    1. Seçilen satırı ve ilgili verileri alın.
    2. Kullanıcıya güncelleme işlemini onaylatan bir iletişim kutusu gösterin.
    3. Kullanıcı onayladıysa, ilgili satır verilerini güncelleyin ve veritabanını güncelleyin.
    4. Tabloyu güncelleyin ve kullanıcıya bir mesaj gösterin.

    İşte guncelle() fonksiyonunun örneği:

    def guncelle(self):
        try:
            selected_items = self.tableWidget.selectedItems()
            if selected_items:
                selected_row = selected_items[0].row()
                musteri_adi = self.lineEdit.text()
                musteri_no = self.lineEdit_2.text()
                sehir = self.lineEdit_3.text()
                musteri_sektor = self.lineEdit_4.text
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.