I want to execute a db query from python:
import MySQLdb
mydb = MySQLdb.connect(host='127.0.0.1', user='root', passwd='', db='macadd', port=3306)
c = mydb.cursor()
c.execute("""INSERT INTO macadd.scanned (mac, first_time_seen, last_time_seen) VALUES (%s, %s, %s)""", ("0A:1B:2C:3D:4E:5F", "2015-09-20 19:00:18", "2015-09-20 19:03:57"))
mydb.close()
print "Done"That's my query to input a value to my database. When I executed, it said done and nothing wrong. But, when I look at the data, nothing comes up. My table is empty.
But when U use the _mysql module:
import _mysql
mydb = _mysql.connect(host='127.0.0.1', user='root', passwd='', db='macadd', port=3306)
mydb.query("INSERT INTO macadd.scanned (mac, first_time_seen, last_time_seen) VALUES ('0A:1B:2C:3D:4E:5F', '2015-09-09 00:00:00', '2015-09-02 00:00:00')")
print "done"It said done as well, nothing wrong, and when when I look at the data, there is one record that has been imported.
Actually I would like to use the MySQLdb module instead of the _mysql one to execute this code:
("""INSERT INTO macadd.scanned (mac, first_time_seen, last_time_seen) VALUES (%s, %s, %s)""", ("0A:1B:2C:3D:4E:5F", "2015-09-20 19:00:18", "2015-09-20 19:03:57"))But, I don't know why it doesn't work. Is there anyone knows how to make this works so I can use MySQLdb module?
71 Answer
Mysql DB supports transaction. According to PEP-249:
"if the database supports an auto-commit feature, this must be initially off" and "closing a connection without committing the changes first will cause an implicit rollback to be performed".
You can
call mydb.commit() to commit your changes to the db
or
(nephente) set autocommit using mydb.autocommit(True)