python拼接sql语句,如何在Python的SQL语句中使用变量和/或连接?

我在名为res的列表中有一个ID列表,在将结果保存到数组中之前,我希望逐行使用该列表作为SQL查询的WHERE条件:ids

grupos

0 [160, 161, 365, 386, 471]

1 [296, 306]

下面是我试图在SQL查询中插入的内容:listado = [None]*len(res)

# We store the hashtags that describes the best the groups

# We iterate on the people of a group to construct the WHERE condition

print "res : ", res

for i in (0,len(res)):

conn = psycopg2.connect(**params)

cur = conn.cursor()

listado = [None]*len(res)

for i in (0,len(res)):

print "res[i:p] : ", res.iloc[i]['ids']

cur.execute("""SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id FROM subscriber_hashtag

-- join para que las publicidades/eclipses que gusta un usarios estan vinculadas con las de la tabla de correspondencia con los hashtag

INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id

-- join para que los usarios estan vinculados con los de la tabla de correspondencia con los hashtag

LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id

-- recobremos los "me gusta"

WHERE subscriber_hastag.subscriber_id in (%s)

GROUP BY subscriber_hashtag.hashtag_id

ORDER BY COUNT(swipe.eclipse_id) DESC;""",(res.iloc[i]['ids']))

n = cur.fetchall()

listado[i] = [{"count": elem[0], "eclipse_id": elem[1]} for elem in n]

可再现示例的数据

提供进一步的数据信息:subscriber_id hashtag_id

160 345

160 347

161 345

160 334

161 347

306 325

296 362

306 324

296 326

161 322

160 322

这里的输出应该是:{0:[324,1],[325,1],[326,1],[362,1], 1 : [345,2],[347,2],[334,1]}

当前错误消息

错误:标记输入时发生意外错误

以下回溯可能已损坏或无效

错误消息是:('EOF in multi-line string',(1,50))---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

in ()

39 WHERE subscriber_hastag.subscriber_id in (%s)

40 GROUP BY subscriber_hashtag.hashtag_id

---> 41 ORDER BY COUNT(swipe.eclipse_id) DESC;""",(res.iloc[i]['ids']))

42

43 n = cur.fetchall()

TypeError:不是所有参数都在字符串格式化期间转换

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值