本例以Windows, Python 3.4 为基础,来演示使用python 来删除My SQL数据库中的数据。

相关

使用Python来完成查询操作:
Python(3.x) Query Record 查询数据

删除数据

my_sql_delete.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import mysql.connector
import my_sql_select

#delete the student by id
def deleteById(config, id):
conn = mysql.connector.Connect(**config)

cur= conn.cursor()

tbl = "STUDENT"
stmt_del = "delete from {0} where id={1}".format(tbl, id)

cur.execute(stmt_del)

conn.commit()

cur.close()
conn.close()


if __name__ == '__main__':

config = {
'host': 'localhost',
'port': 3306,
'database': 'test',
'user': 'root',
'password': '!qaz2wsx',
'charset': 'utf8',
'use_unicode': True,
'get_warnings': True,
}

print("----------before delete------------")
output = my_sql_select.queryAllStu(config)
print('\n'.join(output))

deleteById(config, 1)

print("----------after delete------------")

output = my_sql_select.queryAllStu(config)
print('\n'.join(output))

运行结果:

1
2
3
4
5
----------before delete------------
1 | Jack | 22 | 1990-03-27 | 2017-06-25 00:25:32
2 | Zhao San | 21 | 1995-10-21 | 2017-06-25 00:25:32
----------after delete------------
2 | Zhao San | 21 | 1995-10-21 | 2017-06-25 00:25:32