Python MySQLDB Insert with variables as parameters

别等时光非礼了梦想. 提交于 2019-12-11 03:08:35

问题


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()


来源:https://stackoverflow.com/questions/18465411/python-mysqldb-insert-with-variables-as-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!