我已经为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"
在这里,您在ifblock&;中调用db.execute()elif。假设,如果db.execute()返回True,那么它将打印成功添加的字符串。但是db.execute返回False,然后它将转到elif块,再次执行db.execute(),它可以返回True或False,因此,如果它是真,这意味着插入成功,但它不会打印成功消息,但如果它是假,那么它将打印错误:无法添加记录
在else块中,它应该是选择查询
相关问题 更多 >
编程相关推荐