I have a SELECT
query like below in the database table as constant.
select * from dbo.student where dob > @date_of_birth and grade = @grade
I will be getting the parameters and values from a Kafka message for like below and I needs to replace the two parameters with this Kafka message value in Golang. This table and parameters can be different for each query in the database table. So i need to write a generic function to replace the params if any table or any number parameters to be passed.
{
"message": [{
"sql_table": "student",
"input_params": [{
"key": "@date_of_birth",
"value": "2012-03-03"
},
{
"key": "@grade",
"value": "5"
}
]
}
]
}
1条答案
按热度按时间wljmcqd81#
You can use the "github.com/jmoiron/sqlx" library to execute dynamic queries with parameters in Golang. Here's an example code snippet that demonstrates how you can achieve this:
In this code, we first define structs to represent the Kafka message and its contents. We parse the input JSON string into a KafkaMessage object using the encoding/json package.
Next, we loop over each message in the Kafka message and build a parameterized SQL query using the query += fmt.Sprintf("%s = :%d", param.Key, index) statement. The query variable will be replaced with the correct table name and input parameters for each iteration.
We create a map of parameter values called queryParams, which is then passed to the db.NamedQuery() function along with the constructed SQL query string. This function returns an iterator over the matching rows, allowing you to iterate over the results and do whatever you need to do with them.
By using this approach, you can dynamically construct parameterized SQL queries with any number of parameters and execute them safely against your database.