I am trying to pass parameters in cassandra query but I am getting error using python

Viewed 127
 user_input== "b":
       id = input("Enter id of  your book")  
            idnum=int(id)
            column_name = input("Enter column name")
            delete= "delete %(column)s from books where book_id=%(i_d)s"
            session.execute(delete,{'column':column_name,'i_d':id})

I am getting following error while executing this code

Traceback (most recent call last):
File "e:/workspace/library_mangement_application/main.py", line 40, in
delete_data()
File "e:/workspace/library_mangement_application/main.py", line 35, in delete_data
session.execute(delete,{'column':column_name,'i_d':id})
File "cassandra\cluster.py", line 2618, in cassandra.cluster.Session.execute
File "cassandra\cluster.py", line 4894, in cassandra.cluster.ResponseFuture.result
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:7 mismatched input 'book_info' expecting K_FROM (delete ['book_inf]...)">

1 Answers

So Python string formatting isn't a good way to inject variables in CQL. That being said, it's not impossible to do with the column name. So you could do something like this instead:

deleteCQL= "delete %s from books where book_id=?" % column_name

Then create a prepared statement based on deleteCQL, and then bind idnum at query execution time.

pStatement = session.prepare(deleteCQL)
session.execute(pStatement,[idnum])

This approach also helps with escaping any odd characters or punctuation inside the bind variables.

Related