How to delete records from an SQL database using Go?

To delete records from an SQL database using Go, you can follow the following steps:

  1. Import the necessary packages:
import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" )
  1. Create a function that deletes the records:
func deleteRecords() { // Establish a database connection db, err := sql.Open("mysql", "root:password@tcp(localhost:3306)/database_name") if err != nil { panic(err.Error()) } defer db.Close() // Prepare the delete statement stmt, err := db.Prepare("DELETE FROM table_name WHERE condition") if err != nil { panic(err.Error()) } defer stmt.Close() // Execute the delete statement _, err = stmt.Exec() if err != nil { panic(err.Error()) } fmt.Println("Records deleted successfully") }

Replace root:password with your database credentials and database_name, table_name, and condition with the appropriate values.

  1. Call the deleteRecords() function when you want to delete records.

Make sure you have the go-sql-driver/mysql package installed by running go get -u github.com/go-sql-driver/mysql. Adjust the package import based on your database provider.

Remember to handle errors appropriately in a production environment.