Skip to content
Advertisement

Making dynamic SQL queries to a MySQL DB

I’ve never used golang with mysql before, so I’m reading about these for the first time. I’d like to do something like this:

This is far too much typing, especially if I have a dozen more variables I’d like to add to the WHERE condition.

If this were PHP, I’d do something like this:

By using a foreach loop, I can dynamically generate queries and dynamically bind as many variables as needed.

Is something like this an option with golang and mysql? Or are there alternatives to not typing out every single variable combination for a query?

Advertisement

Answer

If you have a map with the field names and values like this:

then you can build the query like this:

This is not susceptible to SQL injection because placeholders are used for parts of the query outside the application’s direct control.

If the map keys are known to be allowed field names, then use this:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement