Using variables to insert
<p>I am new to cassandra and trying to insert in Cassandra keyspace using Python. I have a table mytablecassandra created with cql:</p>

<pre><code>cqlsh:mykeyspace&gt;&gt;CREATE TABLE mytablecassandra(user text PRIMARY KEY, friendlist list&lt;text&gt;);
</code></pre>

<p>Here I read a text file and have variables
<code>auser</code> and
<code>afriend</code></p>

<p>Where these variable have values like</p>

<p><code>auser = 'ABC'</code> and <code>afriend = ['DEF','GHI','JKL']</code></p>

<p>Now I want to insert these variables in my Cassandra table</p>

<pre><code>from cassandra.cluster import Cluster
cluster = Cluster()

session = cluster.connect('mykeyspace')
CQLString = """INSERT INTO mytablecassandra(user,friendlist) VALUES (auser, afriend)"""
session.execute(CQLString);
</code></pre>

<p>And get the error</p>

<blockquote>
  <p>ErrorMessage code=2000 [Syntax error in CQL query] no viable
  alternative at input ')'</p>
</blockquote>

<p>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</p>

<pre><code>CQLString = "INSERT INTO mytablecassandra (user, friendlist) VALUES (%s,%s)"
</code></pre>

<p>then execute it and pass the values in like</p>

<pre><code>session.execute(CQLString, (auser,afriend))
</code></pre>

python cassandra insert