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!