I want to use PartiQL to query a DynamoDB table with boto3. I works perfectly, when I use it like this:
stmt = "SELECT * FROM Onlineshop WHERE PK= 'c#12345'"
resp = dynamodb.execute_statement(Statement= stmt)
But when I replace some values in the select statement with a f-literal it fails.
PK = 'c#12345'
table_name = 'Onlineshop'
stmt = f' "SELECT * FROM {table_name} WHERE PK= {PK}" '
resp = dynamodb.execute_statement(Statement= stmt)
What could be the reason?
Thank you in advance
W
The originally-accepted answer suffers from a potential SQL injection problem so I've added this alternate answer. You should always pass parameters safely.
PK = "c#12345"
resp = dynamodb.execute_statement(
Statement="SELECT * FROM Onlineshop WHERE PK=?",
Parameters=[
{
"S": PK
}
]
)
Arguably, you could inject the table name Onlineshop
via f-string, as in the OP's original self-answer, but that's only safe if the table name was not provided by a user (or other external entity). I'd personally prefer to see the table name hard-coded.