【问题标题】:insertion of a list in cassandra python在 cassandra python 中插入列表
【发布时间】:2017-06-28 08:48:35
【问题描述】:

我在 Cassandra 有一张桌子,例如:

CREATE TABLE IF NOT EXISTS article(
         url text PRIMARY KEY, 
         title text, 
         author text, 
         sources list<text>)

我有一个对象Article,它使用以下方法将数据插入到cassandra:

def save_to_cassandra(self, session):
    session.execute(
        """
        INSERT INTO article (url, title, author, sources)
        VALUES (%s, %s, %s, ????)
        """,
        (self.url, self.title, self.author, ["http://source1.com", "http://source2.com"])
    )

问题是我应该使用什么来代替???? 来正确格式化字符串

【问题讨论】:

    标签: python database string cassandra formatting


    【解决方案1】:

    您应该将 %s 用于所有类型的参数,而不仅仅是字符串
    所以使用 %s,这里是完整的代码

    def save_to_cassandra(self, session):
        session.execute(
            """
            INSERT INTO article (url, title, author, sources)
            VALUES (%s, %s, %s, %s)
            """,
            (self.url, self.title, self.author, ["http://source1.com", "http://source2.com"])
        )
    

    来源:http://datastax.github.io/python-driver/getting_started.html#passing-parameters-to-cql-queries

    另外,你应该总是使用准备好的语句

    Prepared statements 是由 Cassandra 解析然后保存以供以后使用的查询。当驱动程序使用准备好的语句时,它只需将参数的值发送到绑定。这降低了 Cassandra 中的网络流量和 CPU 利用率,因为 Cassandra 不必每次都重新解析查询。

    【讨论】:

      猜你喜欢
      • 2016-07-06
      • 2016-09-05
      • 1970-01-01
      • 2018-12-31
      • 2020-11-04
      • 1970-01-01
      • 2013-03-26
      • 2014-04-18
      • 1970-01-01
      相关资源
      最近更新 更多