To use placeholders for parameterized queries in Go with SQL databases, you can follow these steps:
Use the database/sql
package to connect and interact with the SQL database.
Prepare the SQL statement with placeholders using the Prepare
method of the *sql.DB
or *sql.Tx
object. For example:
stmt, err := db.Prepare("INSERT INTO users(name, email) VALUES(?, ?)")
if err != nil {
// handle the error
}
defer stmt.Close()
Exec
method on the prepared statement object. Provide the values for the placeholders as arguments to the Exec
method. For example:name := "John Doe"
email := "[email protected]"
result, err := stmt.Exec(name, email)
if err != nil {
// handle the error
}
affectedRows, err := result.RowsAffected()
if err != nil {
// handle the error
}
fmt.Printf("Inserted %d row(s)\n", affectedRows)
stmt, err := db.Prepare("SELECT name, email FROM users where id = ?")
if err != nil {
// handle the error
}
defer stmt.Close()
id := 1
rows, err := stmt.Query(id)
if err != nil {
// handle the error
}
defer rows.Close()
for rows.Next() {
var name, email string
err := rows.Scan(&name, &email)
if err != nil {
// handle the error
}
fmt.Printf("Name: %s, Email: %s\n", name, email)
}
By using placeholders in parameterized queries, you can prevent SQL injection attacks and improve the security and performance of your application.