我如何跳过 python flask mysql 连接器中提供给 %s 的空值

how do i skip empty values supplied to %s in python flask mysql connector

例如,我正在查询我的数据库

try:
            dbConn = DatabasePool.getConnection()
            cursor = dbConn.cursor(dictionary=True)
            sqlquery = f"update table set name=%s if(name=%s is not null),description=%s if(description=%s is not null) where jsonid=%s"
            cursor.execute(
                sqlquery, (JSON['name'], JSON['description'], jsonid))

            dbConn.commit()
            rows = cursor.rowcount
            return rows

        finally:
            dbConn.close()

如果我将名称字段留空。我仍然可以为我的名字更新我的描述。

我该如何使用 %s

我也试过另一种方法

sql = f"update table set name=if(name is null, name, %s), description = if(description is null, description, %s) where jsonID=%s"
            cursor.execute(
                sql, (JSON['name'], JSON['description'], jsonid))

我必须提供这 2 个字段,否则如果其中一个字段较少,它会抛出 500 内部服务器错误。

如果您要更新的字段集是可变的,那么您需要动态构建查询。请注意,我根据存在的字段添加了额外的“SET”子句。

        clauses = []
        values = []
        if JSON['name']:
            clauses.append( 'name=%s' )
            values.append( JSON['name'] )
        if JSON['description']:
            clauses.append( 'description=%s' )
            values.append( JSON['description'] )
        if values:
            values.append( jsonid )
            cursor = dbConn.cursor(dictionary=True)
            sqlquery = "UPDATE table SET " + (','.join(clauses)) + " WHERE jsonid=%s;"
            cursor.execute( sqlquery, values )
            rows = cursor.rowcount
            dbConn.commit()
            return rows

如果您不仅有这两个字段,还可以使其更加自动化:

        for column in ('name','description'):
            if JSON[column]:
                clauses.append( column + '=%s' )
                values.append( JSON[column] )