【问题标题】:Pass values from python list to Cassandra query将值从 python 列表传递到 Cassandra 查询
【发布时间】:2018-02-22 09:34:03
【问题描述】:

这里是初学者。 我有以下情况。

  • 每行包含一个名称的文本文件。
  • cassandra 3.5 数据库
  • python 脚本

目的是让脚本一次从文件中读取一行(一个名称),并使用该名称查询 Cassandra。

仅供参考,除了我尝试将列表的值传递给查询时,一切正常。

我目前有类似的东西:

#... driver import, datetime imports done above
#...

with open(fname) as f:
content = f.readlines()

# Loop for each line from the number of lines in the name list file
# num_of_lines is already set
for x in range(num_of_lines):
    tagname = str(content[x])

    rows = session.execute("""SELECT * FROM tablename where name = %s and date = %s order by time desc limit 1""", (tagname, startDay))
    for row in rows:
        print row.name + ", " + str(row.date)

如果我删除 tagname 列表组件并使用名称值编辑查询本身,一切正常。

我在这里做错了什么?

【问题讨论】:

  • 你得到了什么异常? NameError: name 'tagname' is not defined?
  • 还有tagname = str(content[x])的期望值是多少?这可能是无,而且是根本原因。
  • @Vinny 不幸的是,我没有收到任何错误。打印 row.name.... 根本没有打印。完全没有错误。现在,tagname = str(content[x]) 不是没有。打印标记名完美运行。

标签: python python-2.7 cassandra


【解决方案1】:

简单地建立在上面@Vinny 的答案之上,格式只是替换了文字值。你需要在它周围加上引号。

for x in content:
    rows = session.execute("SELECT * FROM tablename where name ='{}' and date ='{}' order by time desc limit 1".format(x, startDay))
    for row in rows:
        print row.name + ", " + str(row.date)

【讨论】:

    【解决方案2】:

    你可以简单地遍历content

    for x in content:
    
        rows = session.execute("SELECT * FROM tablename where name = {} and date = {} order by time desc limit 1".format(x, startDay))
        for row in rows:
            print row.name + ", " + str(row.date)
        ....
    

    此外,您不需要为字符串添加 3 个引号。单引号就足够了(3个引号用于文档/python中的多行cmets)

    请注意,这可能会以不同的错误结束;但是您将在行上进行迭代,而不是在索引上进行迭代并读取行。

    【讨论】:

    • 谢谢。三引号,多行。知道了。我修改了代码。它帮助我避免阅读行数。在查询中,我根据您的 sn-p 将 %s 更改为 {}。我现在收到以下错误:TypeError: not all arguments converted during string formatting
    • @bshakya 可能是你有一个 None 对象。在原始打印之前使用调试打印检查标签名称 print type(x) 的类型
    • 观察。 print x 显然在其末尾包含一个 \n 。因此,当我打印它时,我也可以看到正在打印的新行。我认为这可能是问题所在?如何删除它并将值转换为纯字符串?
    • print type(x)的输出为:<type 'str'>
    猜你喜欢
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    相关资源
    最近更新 更多