Search code examples
pythondatabaseprepared-statementgriddb

How to Execute Parameterized Queries in GridDB Using the Python Client?


I'm using the GridDB Python client to interact with my time-series data. I want to execute a parameterized query to prevent SQL injection and handle dynamic values efficiently. When I run the code I get this error:

[0] -1: Parameter index out of range

Here's the code I'm working with:

from griddb_python import griddb



# Initialize GridStore factory
factory = griddb.StoreFactory.get_instance()



try:
# Connect to the GridStore
gridstore = factory.get_store(
host='239.0.0.1',
port=31999,
cluster_name='defaultCluster',
username='admin',
password='admin'
)



# Get the container
container = gridstore.get_container("sensor_data")



# Create a parameterized query
query = container.query("SELECT * FROM sensor_data WHERE sensor_id = ?")



# Set the parameter value
query.set_parameter(1, 'sensor_123')



# Execute the query
rs = query.fetch()



# Process the result set
while rs.has_next():
data = http://rs.next()
print(data)



except griddb.GSException as e:
for i in range(e.get_error_stack_size()):
print(f"[{i}] {e.get_error_code(i)}: {e.get_message(i)}")

Solution

  • In your code you have set the query.set_parameter(1, 'sensor_123') value 1 which results in the "Parameter index out of range" error as already mentioned in your error code. Change this value from 1 to 0 and i am sure your issue will be resolved.