欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PyMySQL的更新 UPDATE

程序员文章站 2022-06-01 13:29:41
...
import pymysql


class Oper_Sql:
    # 更新语句
    update_sql = 'update self_user set name="other" where id="1001" '


def main():
    try:
        conn = pymysql.connect(host='localhost',
                               user='root',
                               password='root',
                               db='scott',
                               charset='utf8'
                               )
        with conn.cursor() as cursor:
            cursor.execute(Oper_Sql.update_sql)
            # 必须有 conn.commit() 否则数据库不能得到执行结果
            conn.commit()
            print('更新成功!')
    except Exception as err:
        print(err)
    finally:
        conn.close()


if __name__ == '__main__':
    main()

  • 原始表数据
	-- 要修改的原始数据
	mysql> select * from self_user where id='1001';
	+------+-------+------+------+------------+
	| id   | name  | sex  | age  | birthday   |
	+------+-------+------+------+------------+
	| 1001 | aidou | male | 32   | 2020-02-23 |
	+------+-------+------+------+------------+
	1 row in set (0.00 sec)
	
	
	mysql> select * from self_user;
	+------+-------+--------+------+------------+
	| id   | name  | sex    | age  | birthday   |
	+------+-------+--------+------+------------+
	| 1001 | aidou | male   | 32   | 2020-02-23 |
	| 1002 | moli  | female | 12   | 2020-03-23 |
	| 1003 | ali   | male   | 32   | 2020-03-04 |
	| 1004 | boby  | male   | 19   | 1996-05-04 |
	| 0001 | nihao | male   | 43   | 2020-03-21 |
	+------+-------+--------+------+------------+
	5 rows in set (0.00 sec)
  • 执行更新后的数据(更新 ID = '1001' name = other
  • 结果提示: 更新成功!
	mysql> select * from self_user;
	
	+------+-------+--------+------+------------+
	| id   | name  | sex    | age  | birthday   |
	+------+-------+--------+------+------------+
	| 1001 | other | male   | 32   | 2020-02-23 |
	| 1002 | moli  | female | 12   | 2020-03-23 |
	| 1003 | ali   | male   | 32   | 2020-03-04 |
	| 1004 | boby  | male   | 19   | 1996-05-04 |
	| 0001 | nihao | male   | 43   | 2020-03-21 |
	+------+-------+--------+------+------------+
	5 rows in set (0.00 sec)

	-- 抽离出执行成功的 SQL 
	mysql> select * from self_user where id=1001;
	+------+-------+------+------+------------+
	| id   | name  | sex  | age  | birthday   |
	+------+-------+------+------+------------+
	| 1001 | other | male | 32   | 2020-02-23 |
	+------+-------+------+------+------------+
相关标签: PyMySQL之 UPDATE