我的查询:
SELECT *
FROM employee.emp_details
WHERE id = 7
这是我的代码
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))
这是我得到的错误:
追踪(最近的呼叫最后):
文件" /home/sachhya/Documents/Example/ex.py" ;,第9行,中
rows = session.execute(''' SELECT *%s employee.emp_details WHERE id =%s''',(val,7))
文件" /usr/local/lib/python3.6/dist-packages/cassandra/cluster.py" ;,第2134行,执行中
return self.execute_async(query,parameters,trace,custom_payload,timeout,execution_profile,paging_state).result()
文件" /usr/local/lib/python3.6/dist-packages/cassandra/cluster.py" ;,第4026行,结果
提升self._final_exception
cassandra.protocol.SyntaxException:
我相信我的查询字符串是在参数绑定之后做出的。 SELECT * 'FROM' employee.emp_details WHERE id = 7
请帮助我使用' val'要在我的查询字符串中绑定的变量。
答案 0 :(得分:0)
从技术上讲,您不必在查询中绑定FROM。在这种情况下使用字符串格式:
rows = session.execute('''SELECT * {} employee.emp_details WHERE id = %s'''.format(val), (7,))
答案 1 :(得分:0)
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)
来自终端的输出:
>>> 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'
答案 2 :(得分:0)
让我告诉你预备陈述的力量。
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
在必须迭代查询中的变量时使用预备语句。