在Python

时间:2017-11-11 01:20:57

标签: python mysql

我刚进入SQL做一些数据科学,并想知道为什么我的代码在运行但不会以任何方式影响MySQL数据库。我正在使用pycharm和MySQLdb模块。

 import MySQLdb
 db = MySQLdb.connect(host="localhost",
                      user="root",
                      passwd="********", #Password blocked
                      db="test")
 cur = db.cursor()
 cur.execute("SELECT * FROM movies")
 cur.execute("Update movies set genre = 'action' where id = 1")
 for row in cur.fetchall() :
     print row[0], " ", row[1], " ", row[2]

我的代码运行并且没有返回错误,但是当我删除

 cur.execute("Update movies set genre = 'action' where id = 1")

它只是打印出以前的表格。仅供参考,以下是表格:

1星际科幻

2 Thor:Ragnarok行动

3托尔:黑暗世界的行动

如何让python中的命令实际影响表?非常感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

您必须使用cur.commit()

提交对表格所做的更改

Database does not update automatically with MySQL and Python

答案 1 :(得分:0)

使用cur.commit()将更改提交到数据库。此外,您应该在完成后使用cur.close()关闭数据库。