【问题标题】:python SQL query insert shows empty rowspython SQL查询插入显示空行
【发布时间】:2016-09-11 17:46:21
【问题描述】:

我正在尝试在 SQL 中执行插入查询。它表示它成功但在数据库中没有显示记录。这是我的代码

conn = MySQLdb.connect("localhost",self.user,"",self.db)
cursor = conn.cursor()
id_val = 123456;
path_val = "/homes/error.path"
host_val = "123.23.45.64"
time_val = 7
cursor.execute("INSERT INTO success (id,path,hostname,time_elapsed) VALUES (%s,%s,%s,%s)", (id_val, path_val,host_val,time_val))

print "query executed"
rows = cursor.fetchall()
print rows

这会输出以下内容

query executed
()

它没有给我任何错误,但数据库似乎是空的。我在 mysql 控制台中尝试了我的 SQL 查询。执行以下命令。

INSERT INTO success (id,path,hostname,time_elapsed)
VALUES (1,'sometext','hosttext',4);

这很好,因为我可以看到数据库已填充。

mysql> SELECT * FROM success LIMIT 5;
+----+----------+----------+--------------+
| id | path     | hostname | time_elapsed |
+----+----------+----------+--------------+
|  1 | sometext | hosttext |            4 |
+----+----------+----------+--------------+

所以我猜 SQL 查询命令是对的。不知道为什么我的cursor.execute 没有响应。有人可以指出我正确的方向。似乎无法找出错误。谢谢

【问题讨论】:

    标签: python mysql python-2.7 mysql-python


    【解决方案1】:

    在您发送 INSERT 记录后,您应该在数据库中提交您的更改:

    cursor.execute("INSERT INTO success (id,path,hostname,time_elapsed) VALUES (%s,%s,%s,%s)", (id_val, path_val,host_val,time_val))
    conn.commit()
    

    当您想要读取数据时,您应该首先发送您的查询,就像通过您的解释器所做的那样。

    所以在获取数据之前,请执行 SELECT 命令:

    cursor.execute("SELECT * FROM success")
    rows = cursor.fetchall()
    print rows
    

    如果你想做pythonic:

    cursor.execute("SELECT * FROM success")
    for row in cursor:
        print(row)
    

    【讨论】:

      猜你喜欢
      • 2016-04-04
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多