gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:16:52 27 4
gpt4 key购买 nike

如何获得这些 SQL 语句序列?上类?我以前只处理过单个 select 语句,而 cursor.execute 工作得很好。我现在不知道在这种情况下该怎么办。我收到的错误是格式需要映射

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)

最佳答案

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

我们还假设它支持一个“操作”中的多个语句。注意:第三条语句(SELECT ... UNION ALL SELECT ...)末尾缺少分号。

在这种情况下,您需要做的就是使用 cursor.execute(sql, args) ... executemany() 与一系列 args (例如执行多个 INSERT)。

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

使用三引号(和结构化缩进而不是宽缩进)将使您的 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;
"""

关于python - 在我的情况下如何使用 Executemany?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5935786/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com