How can be determined whether a record exists in a table? The way I tried was to do a SELECT
query and then count the rows of the ResultSet
using the following:
rows = session.execute("SELECT * FROM test_table WHERE id=%s", ([<id_here>]))
if len(rows) == 0:
print "Does not exist"
However, ResultSet
does not support len
. In another answer, they suggest to use SELECT COUNT(*)
which in another reference is strongly discouraged. Is there a more standard way to do this?
You can simply do one of the following:
rows = session.execute("SELECT * FROM test_table WHERE id=%s", ([<id_here>]))
if not rows:
print "Does not exist"
Or, if selecting multiple rows you could iterate over the ResultSet with:
for row in rows:
do_something(row)
ResultSet also has a current_rows attribute which will be empty if none were returned.
See http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.ResultSet for more details on how to use the ResultSet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With