Mysql 查询在 wamp 服务器 mysql 控制台中运行,但不通过 python 文件或控制台运行



我用python编写了这段代码

import MySQLdb

mydb = MySQLdb.connect(host='localhost',
    user='root',
    passwd='',
    db='tifetal')
cursor = mydb.cursor()
sql ="select one_number,two_number, one_number * two_number as 'multiplied_number' from multiply_test"
cursor.execute(sql)
mydb.commit()
cursor.close()
print "Done"

我的专栏看起来像

+------------+------------+-------------------+
| one_number | two_number | multiplied_number |
+------------+------------+-------------------+
| 11         | 12         | NULL              |
| 13         | 24         | NULL              |
+------------+------------+-------------------+

如果我在 mysqlconsole 中运行它,它可以完美运行

+------------+------------+-------------------+
| one_number | two_number | multiplied_number |
+------------+------------+-------------------+
| 11         | 12         |               132 |
| 13         | 24         |               312 |
+------------+------------+-------------------+
2 rows in set (0.00 sec)

但是在执行 Python 代码时,multiplied_number列仍然是 nulll 。

我有蟒蛇版本

Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

我有窗户 10

如果我能克服这个问题,我会很高兴。我不明白发生了什么。 好的,我已经从ikac那里得到了答案。谢谢伙计..请对IKAC给出的答案投赞成票...

import MySQLdb
mydb = MySQLdb.connect(host='localhost',
                       user='root',
                       passwd='',
                       db='tifetal')
cursor = mydb.cursor()
sql = "update multiply_test set multiplied_number = one_number * two_number"
cursor.execute(sql)
mydb.commit()
cursor.close()
print "Done"

当您在 mysql 控制台中运行给定查询时,它会显示的表只是查询的结果。该表不存在,现有表也不会更新。在 Python 代码中给定查询后执行commit也不会更新表。

您的意图是什么,更新表或只是将相乘的列作为查询结果中的新列?

编辑 1.

好的,所以正如我所理解的,你只希望结果列在 Python 代码中使用。这是你如何得到它。

import MySQLdb
mydb = MySQLdb.connect(host='localhost',
                       user='root',
                       passwd='',
                       db='tifetal')
cursor = mydb.cursor()
sql = "select one_number,two_number, one_number * two_number as 'multiplied_number' from multiply_test"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
    print row
cursor.close()
print "Done"

编辑 2.

所以我理解你错了。这是您更新表的方式。

import MySQLdb
mydb = MySQLdb.connect(host='localhost',
                       user='root',
                       passwd='',
                       db='tifetal')
cursor = mydb.cursor()
sql = "update multiply_test set multiplied_number = one_number * two_number"
cursor.execute(sql)
mydb.commit()
cursor.close()
print "Done"

最新更新