繁体   English   中英

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

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

我正在使用python 2.7和MySQL作为数据库。 在我的python程序中有一个INSERT查询,如下所示:

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

当我签入数据库时​​,没有任何条目。 但是在我的python代码中选择之后,当我打印结果时,它会显示插入的数据。 我也不使用任何交易记录。

您需要为数据库提交事务以使插入成为永久性的,并且需要使用SQL参数来防止SQL注入攻击和一般的引用错误:

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

在提交之前,插入的数据仅对python程序可见; 如果根本不提交,则数据库再次放弃所做的更改。

或者,您可以打开自动提交模式:

connection.autocommit()

开启自动提交后,您的插入内容将立即被提交。 请注意这一点,因为如果您需要将数据插入到相互依赖的多行和/或表中,则可能导致数据不一致。

您还需要在执行语句之后提交数据。 在完成插入或更新数据后调用此方法很重要,因为默认情况下 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()

如果使用mysql-python,则可以设置连接选项以启用自动提交功能。

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

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

您可以在此处查看更多详细信息

暂无
暂无

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

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