bikas bikas - 1 month ago 4x
Python Question

Using variables to insert

I am new to cassandra and trying to insert in Cassandra keyspace using Python. I have a table mytablecassandra created with cql:

cqlsh:mykeyspace>>CREATE TABLE mytablecassandra(user text PRIMARY KEY, friendlist list<text>);

Here I read a text file and have variables

Where these variable have values like

auser = 'ABC'
afriend = ['DEF','GHI','JKL']

Now I want to insert these variables in my Cassandra table

from cassandra.cluster import Cluster
cluster = Cluster()

session = cluster.connect('mykeyspace')
CQLString = """INSERT INTO mytablecassandra(user,friendlist) VALUES (auser, afriend)"""

And get the error

ErrorMessage code=2000 [Syntax error in CQL query] no viable
alternative at input ')'


Your strings don't get expanded in place that way, nor is it really the recommended way (that way lies SQL injection attacks often). Instead you should make your query string have place holders for the values like

CQLString = "INSERT INTO mytablecassandra (user, friendlist) VALUES (%s,%s)"

then execute it and pass the values in like

session.execute(CQLString, (auser,afriend))