Python MySQLDB Insert with variables as parameters

2019-07-11 11:43发布

问题:

I am using Python-MySQLdB library.

I am trying to connect to the MySQL DB from a python script. I have a requirement where when the users register their account automatically the details should be added/saved to the MySQL DB. I'm trying to automate this feature using python.

The script is running successfully and the values are not reflected in the DB. What might be the issue ??

This is the script.

import sys
import MySQLdb as mdb
import datetime
username ='trail'
password='trial'
companyname="trialuser"
imei = '0'
tval = 'T'
try:
    con = mdb.connect('localhost', 'root', 'test', 'collect');
    cur = con.cursor()
    currdate = d = datetime.date.today() + datetime.timedelta(days=30)  
    cur.execute("""
INSERT INTO user (companyName,user,pass,imei, checkPoint,licenceDate) VALUES (%s,%s,%s,%s,%s,%s) """,(companyname,username, password,imei,tval,currdate))
    print 'Succesfully Inserted the values to DB !' 
except mdb.Error, e:
    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)   
finally:    
    if con:    
       con.close()

回答1:

I got it!

I had missed the commit() function. We have to call commit after a transaction to save the changes to DB:

con.commit()