"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Safely Concatenate Strings in SQL Queries with Go?

How to Safely Concatenate Strings in SQL Queries with Go?

Published on 2024-11-03
Browse:629

How to Safely Concatenate Strings in SQL Queries with Go?

Concatenating Strings in SQL Queries in Go

While text SQL queries offer a straightforward method for querying databases, it's crucial to understand the correct approach to concatenate string literals with values to avoid syntax errors and type mismatches.

The provided query syntax:

query := `SELECT column_name FROM table_name
        WHERE column1_name = %d AND column2_name = %d` % (val1, val2)

results in a syntax error due to the use of Python-style tuples. Instead, employ fmt.Sprintf to concatenate the string and values:

query := fmt.Sprintf(`SELECT column_name FROM table_name
                     WHERE column1_name = %d AND column2_name = %d`, val1, val2)

Alternatively, you can use db.Query to concatenate strings without string interpolation:

query := `SELECT column_name FROM table_name
        WHERE column1_name = %d AND column2_name = %d`

rows, err := db.Query(query, val1, val2)

Remember to address injection vulnerabilities by using prepared statements instead of string interpolation.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3