python - 通过python删除mysql中的行

标签 python mysql python-2.7

我正在尝试通过python在mysql中写一个表:

我想在MYSQL中建表,但删除超过3行,换句话说我只想要3行。例如

emp_no   Num1   Num2   Num3
1          1      2      3
2          1      2      3
3          1      2      3

这些应该删除

4          1      2      3
5          1      2      3
6          1      2      3
.
.
.

我的代码是:

from __future__ import print_function
import mysql.connector
from mysql.connector import errorcode



cnx = mysql.connector.connect(user='',
                              host='localhost')
cursor = cnx.cursor()

DB_NAME = 'DB'
cnx.database = DB_NAME 


TABLES = {}
TABLES['History'] = (
    "CREATE TABLE `History` ("
    "  `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
    "  `Num1` text NOT NULL,"
    "  `Num2` text NOT NULL,"
    "  `Num3` text NOT NULL,"
    "  PRIMARY KEY (`emp_no`)"
    ") ENGINE=InnoDB")


####################33
##
Num1=1
Num2=2
Num3=3

add_employee = ("INSERT INTO History "
               "(Num1, Num2, Num3) "
               "VALUES (%s, %s, %s)")

data_employee = (str(Num1), str(Num2), str(Num3))
### Insert new employee
cursor.execute(add_employee, data_employee)

emp_no = cursor.lastrowid

### Make sure data is committed to the database
cnx.commit()

### *** I use this line for deleting the rows ***
query2 = ("Delete FROM History "
    "WHERE  emp_no >  %s")
cursor.execute(query2, ('3',))


# this part is used for printing the table elements    
query = ("SELECT emp_no, Num1, Num2, Num3 FROM History ")

cursor.execute(query)
#print("last_name")



for (emp_no, Num1, Num2, Num3) in cursor:
 print("{} {} {}".format(
     emp_no, Num1, Num2, Num3))



cursor.close()
cnx.close()
##

例如,当我运行 10 次时,结果始终是:

1 1 2
2 1 2
3 1 2

但是当我注释掉这部分时:

query2 = ("Delete FROM History "
        "WHERE  emp_no >  %s")
    cursor.execute(query2, ('3',))

我看到的很有趣:

1 1 2
2 1 2
3 1 2
4 1 2
5 1 2
6 1 2
7 1 2
8 1 2
9 1 2
10 1 2

超过 3 行的行仍然存在于 Mysql 中,只是在注释掉删除查询之前没有显示出来。

那么如何从 mysql 中完全删除特定行?

最佳答案

您似乎需要调用commit 才能使 DELETE 操作永久生效,就像您在 INSERT 操作之后所做的那样。

关于python - 通过python删除mysql中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12979632/

相关文章:

python - 将设定值组合成一个集合

mysql - python执行sql请求时一直报错

python - 从迭代器获取唯一值的快速方法

python - ncpol2sdpa python工具中出现错误 'OSError: [Errno 2] No such file or directory'的原因是什么?

Python:正确引发异常

python - Utf-8 与 sqlalchemy 在具有 init connect 的数据库上

python - 基于辅助系列从 pandas DataFrame 中进行选择

使用队列的Python多处理死锁

php - 如何解决 Laravel 安装问题。我的开发人员使用 Mac 操作系统,我有 Ubuntu

php - 更新 'pass and confirm' 表单的字段