2017-02-10 77 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不必每次都重新解析查詢。