使用参数将数据插入Spanner

时间:2018-11-01 14:56:20

标签: python google-cloud-platform google-cloud-spanner

我想将变量传递给我的SQL插入语句。 Spanner似乎使用以下语法来指定变量@param。如https://cloud.google.com/spanner/docs/lexical#query-parameters中所述。我是Python的新手,所以我认为我不太了解语法,因为它引发错误“找不到绑定参数:messageid”。相同的代码使用硬编码值可以正确执行。

这是我的代码:

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)"
    )

更新:如果有人感兴趣,这是工作代码

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

1 个答案:

答案 0 :(得分:0)