I want to pass variables to my SQL insert statement. Spanner seems to use the following syntax to specify a variable @param. As described in https://cloud.google.com/spanner/docs/lexical#query-parameters. I am new to Python so I don't think I am quite understand the syntax because it throws the error "No parameter found for binding: messageid" The same code executes correctly with hard coded values.
Here is my code:
messageid = str(uuid.uuid4())
sender = newmsg['Sender']
recipient = newmsg['Recipient']
message = newmsg['Message']
def insert_message(transaction):
self.logger.debug("Inside insert_with_dml")
row_ct = transaction.execute_update(
"INSERT MESSAGE_STORE (MessageId, Message, MessageRecipient, MessageSender) "
" VALUES (@messageid, @message, @recipient, @sender)"
)
Update: Here is the working code if anyone is interested
def insertmessage(self, newmsg):
messageid = str(uuid.uuid4())
sender = newmsg['Sender']
recipient = newmsg['Recipient']
message = newmsg['Message']
data_type = param_types.Struct([
param_types.StructField('Id', param_types.STRING),
param_types.StructField('Msg', param_types.STRING),
param_types.StructField('Requestor', param_types.STRING),
param_types.StructField('MsgRecipient', param_types.STRING)
])
data_values = (messageid, message, recipient, sender)
def insert_message(transaction):
self.logger.debug("Inside insert_with_dml")
row_ct = transaction.execute_update(
"INSERT MESSAGE_STORE (MessageId, Message, MessageRecipient, MessageSender) "
"VALUES (@values.Id, @values.Msg, @values.Requestor, @values.MsgRecipient)",
params={'values' : data_values},
param_types={'values' : data_type}
)
self.logger.debug("{} record(s) inserted.".format(row_ct))
try:
self.client.run_in_transaction(insert_message)
except Exception as e:
self.logger.debug(e)
self.logger.debug("Before Output")
output = "{ 'Message Id':" + messageid +", 'Result Code': '1' }"
return output
See the following documentation section on Using STRUCT objects as bound parameters in SQL queries