Python MySQLDB插入,变量作为参数 [英] Python MySQLDB Insert with variables as parameters

查看:203
本文介绍了Python MySQLDB插入,变量作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python-MySQLdB库.

I am using Python-MySQLdB library.

我正在尝试从python脚本连接到MySQL数据库.我有一个要求,当用户自动注册其帐户时,应将详细信息添加/保存到MySQL DB. 我正在尝试使用python自动化此功能.

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 ??

这是脚本.

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

推荐答案

我明白了!

我错过了commit()功能.我们必须在事务处理后调用commit来将更改保存到数据库:

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

con.commit()

这篇关于Python MySQLDB插入,变量作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆