【问题标题】:How to delete or edit only one row in sql table?如何只删除或编辑sql表中的一行?
【发布时间】:2019-02-22 08:13:56
【问题描述】:

that is my app and I used search button to edit information easily 我在 python 中使用该代码向本地数据库添加、删除、更新信息......它在添加信息时运行良好,但是当我使用更新时,数据库中的所有信息或行变得相同。另外,当删除所有数据时,可能是因为使用一个搜索栏来编辑或删除添加的数据

这是我的代码:

import sys
import os
import time

from PyQt5 import QtCore, QtGui, QtWidgets, uic
import mysql.connector
from mysql.connector import errorcode

FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__),"mahmoudtarek.ui"))

class Main(QtWidgets.QMainWindow, FORM_CLASS):
    def __init__(self,parent=None):
        super(Main,self).__init__(parent)
        self.setupUi(self)
        self.InitUI()
        self.conn = None

        self.handle_buttons()
        self.handle_db_connections()

    def InitUI(self):
        ## changes in the run time
        pass

    def handle_buttons(self):
          ## all buttons in the app
        self.pushButton.clicked.connect(self.add_mahmoud_friends)
        self.pushButton_3.clicked.connect(self.update_mahmoud_friends)
        self.pushButton_2.clicked.connect(self.delete_mahmoud_friends)
        self.pushButton_6.clicked.connect(self.search_mahmoud_friends)


    def handle_db_connections(self):
        try:
            self.conn = mysql.connector.connect(
                host='127.0.0.1',
                database='mydb',
                user='root',
                password='134668691011',
                use_pure=True)  # use_pure is set to true

            if self.conn.is_connected():
                db_Info = self.conn.get_server_info()
                print("Connected to MySQL database using C extension... MySQL Server version on ", db_Info)
        except mysql.connector.Error as err:
            print("Error while connecting to MySQL using C extension", err)

    def add_mahmoud_friends(self):
        mth_friends = self.lineEdit.text()
        mth_search = self.lineEdit_4.text()
        if self.conn:
            c = self.conn.cursor()
            try:
                c.execute('''INSERT INTO ahmed (mth_friends,mth_search) values (%s,%s)''', (mth_friends,mth_search))
                self.conn.commit()
                self.lineEdit.setText('')
                self.lineEdit_4.setText('')
                self.statusBar.showMessage('ok mahmoud')


            except mysql.connector.Error as err:
                print("Error: ", err)

    def update_mahmoud_friends(self):
        mth_friends = self.lineEdit.text()
        mth_search = self.lineEdit_4.text()
        if self.conn:
            c = self.conn.cursor()
            try:
                c.execute('''UPDATE ahmed SET mth_friends = %s,mth_search = %s''', (mth_friends, mth_search))
                self.conn.commit()
                self.lineEdit.setText('')
                self.lineEdit_4.setText('')
                self.statusBar.showMessage('ok mahmoud')
                self.lineEdit_3.setText('')


            except mysql.connector.Error as err:
                print("Error: ", err)

    def delete_mahmoud_friends(self):
        c = self.conn.cursor()
        sql = '''DELETE FROM ahmed WHERE mth_search = %s'''
        mth_search = self.lineEdit_3.text()
        c.execute(sql, [(mth_search)])
        self.conn.commit()
        self.statusBar.showMessage("ok")
        self.lineEdit.setText('')
        self.lineEdit_4.setText('')
        self.lineEdit_3.setText('')


    def search_mahmoud_friends(self):
        if self.conn:
            c = self.conn.cursor()

            try:

                sql = '''SELECT * FROM ahmed WHERE mth_search = %s'''
                mth_search = self.lineEdit_3.text()
                c.execute(sql, [(mth_search)])
                data = c.fetchall()
                for row in data :
                    print(row)
                    self.lineEdit.setText(str(row[1]))
                    self.lineEdit_4.setText(str(row[2]))

            except mysql.connector.Error as err:
              print("Error: ", err)

    def closeEvent(self, event):
        if self.conn:
            self.conn.close()
        super(Main, self).closeEvent(event)


def main():
    app= QtWidgets.QApplication(sys.argv)
    window =Main()
    window.show()
    app.exec_()

if __name__ == '__main__':
    main()

我需要帮助,因为我还是个初学者。如果有人知道这个问题,请给我写正确的代码。由于我搜索太多......最后谢谢你

【问题讨论】:

  • 您需要在UPDATE 查询中使用WHERE 子句来告诉它要更新哪些行。
  • “您需要在 UPDATE 查询中使用 WHERE 子句来告诉它要更新哪些行” @Barmar 不要忘记主键或唯一键,因为 topicstarter 只想 @987654327 @或UPDATE一条记录
  • 这只是一个特殊情况,他知道他要更新的行的ID。它可能是同一个朋友的所有行一样的条件。
  • 在那种情况下我必须写什么......请给我一个例子

标签: python mysql python-3.x pycharm mysql-workbench


【解决方案1】:

当你UPDATE时,你需要添加一个条件,否则表格中的每一行都会被这些值更新。

在您的代码中:

c.execute('''UPDATE ahmed SET mth_friends = %s,mth_search = %s''', (mth_friends, mth_search))

应该有一个条件,像这样:

c.execute('''UPDATE ahmed SET mth_friends = %s,mth_search = %s WHERE {ADD CONDITION HERE}''', (mth_friends, mth_search))

如果要更新或删除单个行,则希望条件匹配主键或唯一键列。使用涉及任何其他类型列的条件将更新或删除与该条件匹配的所有行。 (感谢Raymond Nijland

【讨论】:

  • 如果没有 WHERE 子句匹配主键或唯一键列,UPDATE 仍然可以更新多条记录。
  • @RaymondNijland 谢谢,我编辑了答案以反映您的评论。
  • 请给我一个这种情况的例子,因为我不明白
  • @mthafize19 在您的表中,应该有一个带有PRIMARY KEY 约束的整数列。该列使用 ID 唯一标识每一行。如果要更新单行,则条件必须与 PRIMARY KEY 列中该行的 ID 匹配。例如:如果要更新ID为5的行,条件为WHERE ID = 5
  • 我在 mysql 工作台中将 id 设置为自动增量,所以当我添加大量数据时,我必须返回代码并写入它的 id 条件......那是怎么回事? ......必须有另一种方式。 @rdimaio
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-11
  • 1970-01-01
相关资源
最近更新 更多