"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > How can I safely concatenate text and values when constructing SQL queries in Go?

How can I safely concatenate text and values when constructing SQL queries in Go?

2025-03-25에 게시되었습니다
검색:867

How can I safely concatenate text and values when constructing SQL queries in Go?

Concatenating Text and Values in Go SQL Queries

When constructing a text SQL query in Go, there are certain syntax rules to follow when concatenating string and value components, particularly when using integers.

In the Python code provided, the tuple approach is not valid in Go, and attempting to cast parameters as strings will result in type mismatch errors.

The idiomatic way to accomplish this in Go is to use fmt.Sprintf to format the query string. This allows you to embed values within the string at runtime:

query := fmt.Sprintf(`SELECT columnA FROM tableA WHERE columnB = %d AND columnB = %s`,
                     someNumber, someString)

Here, the placeholders %d and %s represent integer and string values, respectively, which are then assigned during the db.Query call:

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

This approach ensures that the values are correctly formatted and prevents SQL injection vulnerabilities.

Avoiding SQL Injection

It is crucial to note that string concatenation in SQL queries can lead to injection vulnerabilities. To mitigate this risk, use prepared statements and parameterized queries. By passing values as parameters, you can prevent malicious input from modifying the intended SQL query.

For example:

stmt, err := db.Prepare(`SELECT columnA FROM tableA WHERE columnB = ? AND columnB = ?`)
rows, err := stmt.Query(val1, val2)

By using prepared statements, you can safeguard your application from malicious SQL input while maintaining the convenience of constructing dynamic queries.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3