0
votes

My query:

SELECT * 
FROM employee.emp_details 
WHERE id = 7

This is my code

from cassandra.cluster import Cluster

HOST = ['10.107.2.123']
PORT = '9042'
cluster = Cluster(HOST, PORT)
session = cluster.connect()

val = 'FROM'
rows = session.execute('''SELECT * %s employee.emp_details WHERE id = %s''', (val, 7))

This is the error that I am getting:

Traceback (most recent call last):
File "/home/sachhya/Documents/Example/ex.py", line 9, in
rows = session.execute('''SELECT * %s employee.emp_details WHERE id = %s''', (val, 7))
File "/usr/local/lib/python3.6/dist-packages/cassandra/cluster.py", line 2134, in execute
return self.execute_async(query, parameters, trace, custom_payload, timeout, execution_profile, paging_state).result()
File "/usr/local/lib/python3.6/dist-packages/cassandra/cluster.py", line 4026, in result
raise self._final_exception
cassandra.protocol.SyntaxException:

I believe that my query string is something made like that after parameter bind. SELECT * 'FROM' employee.emp_details WHERE id = 7

Please help I need to use 'val' variable to bind in my query string.

3
why do you need to bind 'FROM'?Azat Ibrakov

3 Answers

0
votes

Technically, you don't have to bind the FROM in your query. Use string formatting in this case:

rows = session.execute('''SELECT * {} employee.emp_details WHERE id = %s'''.format(val), (7,))
0
votes
from cassandra.cluster import Cluster

HOST = ['10.107.2.123']
PORT = '9042'
cluster = Cluster(HOST, PORT)
session = cluster.connect()

val = 'FROM'
query = 'SELECT * {} employee.emp_details WHERE id = {}'.format(val, 7)

# or query = ('SELECT * %s employee.emp_details WHERE id = %s' % (a, 7))

rows = session.execute(query)

output from terminal:

>>> query = ('SELECT * %s employee.emp_details WHERE id = %s' % (a, 7))
>>> query
'SELECT * FROM employee.emp_details WHERE id = 7'

>>> query = 'SELECT * {} employee.emp_details WHERE id = {}'.format(a, 7)
>>> query
'SELECT * FROM employee.emp_details WHERE id = 7'
0
votes

Let me show you the power of prepared statements.

from cassandra.cluster import Cluster

HOST = ['10.107.2.123'] PORT = '9042' cluster = Cluster(HOST, PORT) session = cluster.connect()

val=7

query="SELECT * employee.emp_details WHERE id = ?" prepared_query=session.prepare(prepared_query)

results=session.execute(prepared_query,(val))

print results

Use Prepared Statements to when you have to iterate through variables in query.

Visit: Prepared Statements Docs