How to execute an INSERT statement in Go to add data to an SQL database?

To execute an INSERT statement in Go to add data to an SQL database, you can follow these steps:

  1. Import the required packages:
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.

  1. Create a new database connection:
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.

  1. Prepare the SQL INSERT statement:
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.

  1. Execute the prepared statement with the values you want to insert:
_, 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.

  1. Handle any errors and confirm the insert was successful:
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.