To delete records from an SQL database using Go, you can follow the following steps:
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
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.
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.