Home >Backend Development >Golang >How to Safely Concatenate Strings in SQL Queries with Go?

How to Safely Concatenate Strings in SQL Queries with Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 21:47:01999browse

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.

The above is the detailed content of How to Safely Concatenate Strings in SQL Queries with Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn