How to use placeholders for parameterized queries in Go with SQL databases?

To use placeholders for parameterized queries in Go with SQL databases, you can follow these steps:

  1. Use the database/sql package to connect and interact with the SQL database.

  2. 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()
  1. Execute the prepared statement by calling the 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)
  1. You can also use placeholders for SELECT queries. Instead of directly including the values in the SQL statement, use placeholders and provide the actual values as arguments when executing the query. For example:
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.