2017-02-10 250 views
0

我有一个表中卡桑德拉像:插入卡桑德拉蟒列表

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

我有一个对象Article用下面的方法来将数据插入到卡桑德拉:

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"]) 
    ) 

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

回答

0

您应该对所有类型的参数使用%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

另一件事,你应该总是使用预处理语句

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