如何使用python中的db类检查sql insert是否添加了任何内容并选择Get something

2024-09-22 14:25:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为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"

Tags: tonameexecutedbsqltableunicodeproduct
1条回答
网友
1楼 · 发布于 2024-09-22 14:25:53
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(),它可以返回TrueFalse,因此,如果它是,这意味着插入成功,但它不会打印成功消息,但如果它是,那么它将打印错误:无法添加记录

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块中,它应该是选择查询

相关问题 更多 >