[Go] Pass parameters to a MySQL query with database/sql
Created on November 30, 2026
With Go's MySQL driver, you can place ? placeholders in a SQL statement and pass the values separately to db.Query. This example looks up a name by user ID. It assumes a MySQL database named example_app with a users table containing id and name columns.
package main
import (
"database/sql"
"fmt"
"github.com/go-sql-driver/mysql"
)
func main() {
config := mysql.NewConfig()
config.User = "app_reader"
config.Passwd = "example-password"
config.Net = "tcp"
config.Addr = "127.0.0.1:3306"
config.DBName = "example_app"
db, err := sql.Open("mysql", config.FormatDSN())
if err != nil {
panic(err)
}
defer db.Close()
rows, err := db.Query("SELECT name FROM users WHERE id = ?", 1)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
panic(err)
}
fmt.Println(name)
}
if err := rows.Err(); err != nil {
panic(err)
}
}
Replace the example connection details with those for your database. The MySQL driver uses a prepared statement by default when binding query arguments. If you plan to run the same statement repeatedly, you can use db.Prepare and reuse the returned statement.