行未添加到数据库中

时间:2014-09-23 11:50:54

标签: python mysql import

我正在使用python将记录添加到数据库中。下面是我的代码,代码不会抛出任何异常,也不会显示任何错误。但我的插入查询不会将任何记录添加到数据库中。我通过打印mysql版本来验证数据库连接。

import MySQLdb
import datetime

db = MySQLdb.connect("localhost","root","pass","selvapractice" )

cursor = db.cursor()

sql = "INSERT INTO setting(username,password,name,settings_createddate,settings_modifieddate) \
       VALUES ('Mac', 'Mohan', 'selva', datetime.datetime.now(), datetime.datetime.now())"
try:
   cursor.execute(sql)
   db.commit()
except: 
   db.rollback()

db.close()

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

考虑:

import MySQLdb
import datetime

db = MySQLdb.connect("localhost","root","pass","selvapractice" )

cursor = db.cursor()

# If client and server times differ, and you want the client timestamp
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
sql = "INSERT INTO setting(username,password,name,settings_createddate,settings_modifieddate) \
       VALUES ('Mac', 'Mohan', 'selva', %s, %s)"  % (now, now)

# If they differ and you want the server timestamp
#   (or if you don't care and want the server timestamp anyway)
sql = "INSERT INTO setting(username,password,name,settings_createddate,settings_modifieddate) \
       VALUES ('Mac', 'Mohan', 'selva', NOW(), NOW())"
try:
    cursor.execute(sql)
    db.commit()
except: 
    db.rollback()
    raise
finally:
    db.close()

请注意,查询(sql)略有不同。 datetime的东西从字符串本身拉出并放在后面。请参阅String Formatting Operations

我还重新提升了数据库异常,因此您可以看到它是什么,并将db.close()放在finally块中。

最后,这也不是最好的方法。某种PDO(可能Python Database Objects)或ORM(可能是peewee)会更好。

答案 1 :(得分:1)

使用%s或%(名称)参数样式指定变量

sql = "INSERT INTO setting(username,password,name,settings_createddate,settings_modifieddate) \
   VALUES (%s, %s, %s %s, %s)"
try:
   args = ('Mac', 'Mohan', 'Mohan', datetime.datetime.now(), datetime.datetime.now())
   cursor.execute(sql, args)
   db.commit()
相关问题