简体   繁体   English

使用python插入后未显示数据库中的数据

[英]Not showing data in database after insertion using python

I am using python 2.7 and MySQL as database. 我正在使用python 2.7和MySQL作为数据库。 In my python program have an INSERT query like this: 在我的python程序中有一个INSERT查询,如下所示:

cursor.execute("insert into login(username,passw)values('"+i.username+"','"+i.password+"')")
result=cursor.execute("select * from login")
print cursor.fetchall()

When I check in the database, there is no entry. 当我签入数据库时​​,没有任何条目。 But after the select in my python code, when I print the results it is showing the inserted data. 但是在我的python代码中选择之后,当我打印结果时,它会显示插入的数据。 I am not using any transaction statement either. 我也不使用任何交易记录。

You need to commit your transaction for the database to make your insert permanent, and you need to use SQL parameters to prevent SQL injection attacks and general quoting bugs: 您需要为数据库提交事务以使插入成为永久性的,并且需要使用SQL参数来防止SQL注入攻击和一般的引用错误:

cursor.execute("insert into login (username, passw) values (%s, %s)", (i.username, i.password))
connection.commit()

Until you commit, the data you inserted will only be visible to your python program; 在提交之前,插入的数据仅对python程序可见; if you do not commit at all, then the changes will be discarded again by the database. 如果根本不提交,则数据库再次放弃所做的更改。

Alternatively, you could switch on auto-commit mode: 或者,您可以打开自动提交模式:

connection.autocommit()

After switching on auto-commit, your insertions will be committed instantly . 开启自动提交后,您的插入内容将立即被提交。 Be careful with this as this could lead to inconsistent data if you need to insert data into multiple rows and / or tables that is interdependent. 请注意这一点,因为如果您需要将数据插入到相互依赖的多行和/或表中,则可能导致数据不一致。

You also need to commit the data after your execution statement. 您还需要在执行语句之后提交数据。 It is important to call this method after you are done inserting, or updating data, as the Python connector does not auto commit by default . 在完成插入或更新数据后调用此方法很重要,因为默认情况下 Python连接器不会自动提交

# Execute & Commit
cursor.execute("insert into login(username,passw) values('%s','%s')", 
               i.username, i.password)
# Commit the insert query!
conn.commit() 

# Fetch Result
result=cursor.execute("select * from login")
print cursor.fetchall()

If you use mysql-python, you can set connection options to enable autocommit feature. 如果使用mysql-python,则可以设置连接选项以启用自动提交功能。

conn = mysql.connection(host, port, autocommit=True)

# or
conn = mysql.connection(host, port)
conn.autocommit(True)

You can see more details here 您可以在此处查看更多详细信息

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

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