如何从Python中的元组中删除尾随逗号

问题描述 投票:0回答:1

我需要您关于如何从元组中删除尾随逗号的建议和帮助。从元组中删除尾随逗号的全部目的是因为我试图执行更新查询语句来更新表中的某些记录。我的查询包含/使用 IN 函数。

所以基本上,我有一个列表 -> 我将列表转换为元组 -> 在我的更新语句中使用它。但尾随逗号阻止我执行查询。我应该在这里更改什么才能使其正常工作?预先感谢。

注意:列表可以有 N 个元素

 transaction_ids_list = ['5b678ujhgfr']

日志显示元组如下所示:

   Original tuple : ('5b678ujhgfr',)
   # the comma at the end of the tuple is preventing me from executing update_query

日志错误

  Exception Occurred -- syntax error at or near ")" LINE 5: ...TRANSACTION_ID IN ('5b678ujhgfr',);

以下代码

    # Connect to the PostgreSQL database
    connection = psycopg2.connect(**db_params)
    print("Connection successfull, for update")
    logging.info("Connection successful for update")
    
    # Convert the list to a tuple for use in the SQL IN clause
    transaction_ids_tuple = tuple(transaction_ids_list)
    print("Original tuple :", transaction_ids_tuple)
    
    # Check if the tuple is not null or empty before executing the update query
    if transaction_ids_tuple:
        update_query = f"""
            UPDATE SCHEMA_X.TABLE124
            SET PUBLISHED = '{current_datetime}',
            EVENT_PUBLISHED = TRUE
            WHERE TRANSACTION_ID IN {transaction_ids_tuple};
        """
        
        # Create a cursor and execute the update query
        with connection.cursor() as cursor:
            cursor.execute(update_query)
            
        # Commit the changes to the database
        connection.commit()
        print("Update successful")
    else:
        print("IDs tuple is null or empty. No update performed.")
sql python-3.x list tuples
1个回答
0
投票

虽然您所要求的在技术上是可行的,但它比使用查询参数更复杂且更不安全。这是一个固定长度的示例,用于演示查询参数化的工作原理:

query = "UPDATE t SET published = %s WHERE transaction_id IN (%s, %s)"
cursor.execute(query, (current_datetime, first_id, second_id))

可以推广到适用于

n
交易 ID:

n_transaction_ids = len(transaction_ids_list)
transaction_id_formats = ("%s",) * n_transaction_ids
transaction_id_format = ", ".join(transaction_id_formats)
query = f"UPDATE t SET published = %s WHERE transaction_id IN ({transaction_id_format})"
cursor.execute(query, (current_datetime, *transaction_ids_list))

显然,您可以消除其中一些中间变量,但我保留它们用于演示目的。

© www.soinside.com 2019 - 2024. All rights reserved.