Python PyMySQL:更新数据


#Python PyMySQL#


建表和数据准备

在 blog 库下建表:

create table `user_info` (
    `id` bigint unsigned not null auto_increment,
    `name` varchar(45) not null default '',
    primary key (`id`)
) engine = InnoDB default charset = utf8mb4;

插入数据,数据内容如下:

mysql> select * from user_info;
+----+---------+
| id | name    |
+----+---------+
|  2 | name001 |
|  3 | name002 |
|  4 | name003 |
|  5 | name004 |
|  6 | name005 |
|  7 | name006 |
+----+---------+
6 rows in set (0.01 sec)

更新数据

import pymysql

conn = pymysql.connect(host='127.0.0.1',
                       user='root',
                       password='123456',
                       port=3306,
                       database='blog',
                       autocommit=True
                       )
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
affect_rows = cursor.execute('update user_info set name=%s where id=%s', ['新名字', 2])

print('影响行数: ', affect_rows)

cursor.close()
conn.close()

运行结果:

影响行数:  1

如果再次执行,运行结果是:

影响行数:  0

为什么影响行数变成0了 ?因为 MySQL 发现要更新的 name 值和已有值相同,就不更新了。


( 本文完 )