简体   繁体   中英

Not showing data in database after insertion using python

I am using python 2.7 and MySQL as database. In my python program have an INSERT query like this:

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. 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:

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; 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 .

# 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.

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

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

You can see more details here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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