简体   繁体   中英

insertion of a list in cassandra python

I have a table in Cassandra like:

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

And I have an object Article with the following method to insert data into 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"])
    )

The question is what should I use instead of the ???? to format properly the string

You should use %s for all types of arguments, not just strings
So use %s, here is the full code

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

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

Another thing, you should always use Prepared Statements

Prepared statements are queries that are parsed by Cassandra and then saved for later use. When the driver uses a prepared statement, it only needs to send the values of parameters to bind. This lowers network traffic and CPU utilization within Cassandra because Cassandra does not have to re-parse the query each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM