我为Python 2.7和MariaDB编写了this database class。并且我想在插入成功时打印消息,或者如果元素不存在且插入失败则打印警告。我应该修改数据库类还是它提供的返回值没问题?这是我的尝试:
def insertProduct (db, name, attrName, attrValue):
sql = 'INSERT IGNORE `product` SET ' + attrName + ' = %s WHERE `name` = %s'
sql2 = """SELECT * FROM `product` WHERE `name` = %s"""
if db.execute (sql, (attrValue, name))['retval']:
print "Successfully added ('" + name + "', '" + attrName + "': " + unicode(attrValue) + ") to `product` table"
elif not db.execute (sql, (attrValue, name))['retval']:
print "ERROR: Couldn't add ('" + name + "', '" + attrName + "': " + unicode(attrValue) + ") to `product` table"
答案 0 :(得分:0)
if db.execute (sql, (attrValue, name))['retval']:
print "Successfully added ('" + name + "', '" + attrName + "': " + unicode(attrValue) + ") to `product` table"
elif not db.execute (**sql**, (attrValue, name))['retval']:
print "ERROR: Couldn't add ('" + name + "', '" + attrName + "': " + unicode(attrValue) + ") to `product` table"
在这里,您在中调用db.execute(),如果阻止&amp;的 elif的即可。假设,如果db.execute()返回 True ,那么它将打印成功添加的字符串。但db.execute返回 False 然后它将转到 elif 块并再次执行db.execute(),它可以返回 True 或< em> False ,所以如果它是 True ,这意味着插入成功但它不会打印成功消息,但如果是 False 那么它将打印错误:无法添加记录。
if db.execute (sql, (attrValue, name))['retval']:
print "Successfully added ('" + name + "', '" + attrName + "': " + unicode(attrValue) + ") to `product` table"
elif not db.execute (**sql2**, (attrValue, name))['retval']:
print "ERROR: Couldn't add ('" + name + "', '" + attrName + "': " + unicode(attrValue) + ") to `product` table"
在else块中,它应该是选择查询