Как исправить ошибку повторяющейся записи в mysqldb-pyqt5 - PullRequest
0 голосов
/ 30 августа 2018

Я изучаю и пытаюсь создать приложение с pyqt5, которое вставляет данные в мою базу данных. Иногда набирается существующий идентификационный номер (первичный ключ), и программа падает ... Я создал следующий код:

from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QLineEdit, 
QPushButton, QMessageBox
import sys
import MySQLdb as mdb 

class Window(QMainWindow):

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

    self.title = "PyQt5 Insert Data"        
    self.top = 100        
    self.left = 100        
    self.width = 680        
    self.height = 400
    self.setWindowIcon(QtGui.QIcon("icon_health.png"))

    self.InitWindow()

  def InitWindow(self):

    self.linedit0 = QLineEdit(self)
    self.linedit0.setPlaceholderText('Please enter your ID')
    self.linedit0.setGeometry(200,50,200,30)

    self.linedit1 = QLineEdit(self)
    self.linedit1.setPlaceholderText('Please enter your name')
    self.linedit1.setGeometry(200,100,200,30)

    self.linedit2 = QLineEdit(self)
    self.linedit2.setPlaceholderText('Please enter your email')
    self.linedit2.setGeometry(200,150,200,30)

    self.linedit3 = QLineEdit(self)
    self.linedit3.setPlaceholderText('Please enter your phone')
    self.linedit3.setGeometry(200,200,200,30)

    self.button = QPushButton("Insert data", self)
    self.button.setGeometry(200,250,100,30)
    self.button.clicked.connect(self.Insertdata)

    self.setWindowIcon(QtGui.QIcon("icon_health.png"))
    self.setWindowTitle(self.title)
    self.setGeometry(self.top, self.left, self.width, self.height)
    self.show()

 def Insertdata (self):
    con = mdb.connect("localhost","root","xxxx","dbname")
    with con:
        cur = con.cursor()
        cur.execute("INSERT INTO data (id, name, email, phone)" 
                     "VALUES('%s','%s','%s','%s')" % (''.join(self.linedit0.text()),
                                                 ''.join(self.linedit1.text()),
                                                 ''.join(self.linedit2.text()),
                                                 ''.join(self.linedit3.text())))
        QMessageBox.about(self, "Connection","Data Inserted Sucessfully")
        self.close()

App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())

Приложение работает хорошо, но когда я набираю дубликат ID, введите (первичный ключ), программа упадет и объявит:

Traceback (most recent call last):
File "C:\Users\oscar\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\MySQLdb\cursors.py", line 250, in execute
self.errorhandler(self, exc, value)
File "C:\Users\oscar\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\MySQLdb\connections.py", line 50, in defaulterrorhandler
raise errorvalue
File "C:\Users\oscar\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\MySQLdb\cursors.py", line 247, in execute
res = self._query(query)
File "C:\Users\oscar\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\MySQLdb\cursors.py", line 411, in _query
rowcount = self._do_query(q)
File "C:\Users\oscar\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\MySQLdb\cursors.py", line 374, in _do_query
db.query(q)
File "C:\Users\oscar\AppData\Local\Programs\Python\Python36-32\lib\site- 
packages\MySQLdb\connections.py", line 277, in query
_mysql.connection.query(self, query)
_mysql_exceptions.IntegrityError: (1062, "Duplicate entry '#######' for key 
'PRIMARY'")
[Finished in 13.2s]

Это немного расстраивает меня. Я намереваюсь найти решение:

try:
   con = mdb.connect("localhost", "root", "xxxxx", "dbname") 
except _mysql.Error as e: 
   QMessageBox.about(self,"Connection", "Duplicate entry for ID")
   sys.exit()

Но вывод остается прежним. Буду признателен за вашу помощь

1 Ответ

0 голосов
/ 30 августа 2018

id столбец автоинкремента, вам не нужно значение для первичного ключа.

cur.execute("INSERT INTO data (name, email, phone)" 
                     "VALUES('%s','%s','%s')" % (
                                                 ''.join(self.linedit1.text()),
                                                 ''.join(self.linedit2.text()),
                                                 ''.join(self.linedit3.text()))) 
...