简体   繁体   English

python SQL查询插入显示空行

[英]python SQL query insert shows empty rows

I am trying to do a insert query in the SQL. 我正在尝试在SQL中执行插入查询。 It indicates that it succeed but shows no record in the database. 它表示成功,但在数据库中未显示任何记录。 Here's my code 这是我的代码

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

this outputs the following 这输出以下

query executed
()

it gives me no errors but the database seems to be empty. 它没有给我任何错误,但是数据库似乎是空的。 I tried my SQL query in the mysql console. 我在mysql控制台中尝试了SQL查询。 executed the following command. 执行以下命令。

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

This works fine as I can see the database got populated. 当我看到数据库已填充时,这可以正常工作。

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

so I am guessing the SQL query command is right. 所以我猜SQL查询命令是正确的。 Not sure why my cursor.execute is not responding. 不知道为什么我的cursor.execute没有响应。 Could someone please point me to the right direction. 有人可以指出我正确的方向。 Can't seem to figure out the bug. 似乎无法找出错误。 thanks 谢谢

After you are sending your INSERT record, you should commit your changes in the database: 发送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()

When you want to read the data, you should first send your query as you did through your interpreter. 当您想读取数据时,首先应该像通过解释器一样发送查询。

So before you fetch the data, execute the SELECT command: 因此,在获取数据之前,请执行SELECT命令:

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

If you want to do it pythonic: 如果您想使用pythonic:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM