如何在我的情况下使用Executemany?

2024-06-01 08:57:32 发布

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

如何获得这些SQL语句序列?去工作?我以前只处理过单个select语句,cursor.execute对此很好。我不知道现在该怎么办。我得到的错误是format requires a mapping

args =  {
        "timepattern" : timepattern,
        "datestart_int" : datestart_int,
        "dateend_int" : dateend_int
        }
sql = ( "CREATE TEMPORARY TABLE cohort_users (user_id INTEGER);                                "
            "INSERT INTO cohort_users (user_id)                                                    "
            "SELECT id FROM users WHERE registered_at BETWEEN %(datestart_int)s AND %(dateend_int)s;                        "
            "SELECT 1, FROM_UNIXTIME(%(dateend_int)s, %(timepattern)s)                                                    "
            "UNION ALL                                                                            "
            "SELECT (COUNT(DISTINCT x.user_id)/(SELECT COUNT(1) FROM cohort_users)),             "
            "        FROM_UNIXTIME((%(dateend_int)s + (7 * 24 * 60 * 60)), %(timepattern)s)                                "
            "FROM cohort_users z INNER JOIN actions x ON x.user_id = z.id                        "
            "WHERE x.did_at BETWEEN (%(datestart_int)s + (7 * 24 * 60 * 60)) AND (%(dateend_int)s + (7 * 24 * 60 * 60))        "
            "DROP TABLE cohort_users;                                                            "
            )

cursor.executemany(sql,args)

Tags: fromidsqltableargs语句selectusers
2条回答

假设您的数据库软件支持形式为%(name)s的参数占位符

我们还假设它在一个“操作”中支持多个语句。注:第三条语句(选择。。。UNION ALL SELECT…)结尾缺少分号。在

在这种情况下,您只需使用cursor.execute(sql, args)。。。executemany()与一系列参数一起使用(例如,执行多个插入)。在

为了便于移植和易于调试,最好一次只执行四个语句。在

使用三重引号(以及结构化缩进而不是宽缩进)将使SQL更易于阅读:

sql = """
CREATE TEMPORARY TABLE cohort_users (user_id INTEGER);   

INSERT INTO cohort_users (user_id)
    SELECT id
        FROM users
        WHERE registered_at BETWEEN %(datestart_int)s AND %(dateend_int)s
    ;

SELECT  1, FROM_UNIXTIME(%(dateend_int)s, %(timepattern)s)
UNION ALL
SELECT  (COUNT(DISTINCT x.user_id)/(SELECT COUNT(1) FROM cohort_users)), 
        FROM_UNIXTIME((%(dateend_int)s + (7 * 24 * 60 * 60)), (timepattern)s)
    FROM cohort_users z
    INNER JOIN actions x ON x.user_id = z.id
    WHERE x.did_at BETWEEN (%(datestart_int)s + (7 * 24 * 60 * 60))
    AND (%(dateend_int)s + (7 * 24 * 60 * 60))
    ;

DROP TABLE cohort_users;
"""

executemany()用于对多个参数执行同一个语句。在

您需要的是另一种方法:只需对每个语句调用execute()。在

相关问题 更多 >