To execute an INSERT statement in Go to add data to an SQL database, you can follow these steps:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
Make sure you have the necessary driver package installed. In this example, we are using the MySQL driver.
db, err := sql.Open("mysql", "user:password@tcp(host:port)/database")
if err != nil {
panic(err)
}
defer db.Close()
Replace user
, password
, host
, port
, and database
with the appropriate values for your database connection.
stmt, err := db.Prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)")
if err != nil {
panic(err)
}
defer stmt.Close()
Replace table_name
with the name of your table and column1
, column2
with the columns to which you want to add data.
_, err = stmt.Exec(value1, value2)
if err != nil {
panic(err)
}
Replace value1
, value2
with the actual values you want to insert into the respective columns.
if err != nil {
panic(err)
} else {
fmt.Println("Data inserted successfully.")
}
Remember to handle any potential errors that might occur during the execution of the INSERT statement.