Home > Article > Backend Development > How to Safely Construct Text SQL Queries in Go?
When writing text SQL queries in Go, you might encounter issues while concatenating string portions with values. Traditional methods, such as using %d and %s placeholders within a string, may lead to syntax errors or type mismatches.
Python-Style Concatenation
In Python, you can concatenate strings and values using % operators within triple-quoted strings. However, this approach is not supported in Go.
Go Equivalent
To achieve similar concatenation in Go, you can use the fmt.Sprintf function. It takes a string format as the first argument and additional arguments for the placeholders:
<code class="go">query := fmt.Sprintf(`SELECT columnA FROM tableA WHERE columnB = %d AND columnC = %s`, someNumber, someString)</code>
Preventing Injection Vulnerabilities
While concatenating values into queries, it's crucial to avoid injection vulnerabilities. Instead of using placeholders within strings, consider using prepared statements:
<code class="go">query := `SELECT columnA FROM tableA WHERE columnB = ? AND columnC = ?` rows, err := db.Query(query, val1, val2)</code>
Here, ? placeholders represent the values, and val1 and val2 are passed as arguments to db.Query. This method ensures query safety and prevents malicious input from affecting the database.
The above is the detailed content of How to Safely Construct Text SQL Queries in Go?. For more information, please follow other related articles on the PHP Chinese website!