Golang - MySQL Delete Example

In this source code example, we show how to delete data from the MySQL database table in Golang with an example.

All Golang source code examples at https://www.sourcecodeexamples.net/p/golang-source-code-examples.html

Required package

To connect to MySQL we need a driver. Here is the driver that we are going to use.

To install it into GOPATH we simply run this command:

G:\GoLang\examples>go get -u github.com/go-sql-driver/mysql

Database Set up

Let's use below SQL statement to create a database in the MySQL server:

create database demo

After creating the database, use the below SQL script to create a students table in the database:

CREATE TABLE `students` (
  `email` varchar(255) DEFAULT NULL,
  `first_name` varchar(255) DEFAULT NULL,
  `last_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)

Insert Data

Let's use the below example to insert data into students table and then we will be able to delete data from a database.

Golang - MySQL Insert Example

Golang - MySQL Delete Example

In this example, we will delete the first record in students table.

Let's create a file named "go_example.go" and add the following content to it:

package main
import (
    _ "github.com/go-sql-driver/mysql"
type Student struct {
    Id         int
    Email       string
    First_Name string
	Last_Name string
func main() {
	db, e := sql.Open("mysql", "root:root@tcp(")
    // close database after all work is done
    defer db.Close()
    // delete data
    stmt, e := db.Prepare("delete from students where id=?")
    // delete 1st student
    res, e := stmt.Exec("1")
    // affected rows
    a, e := res.RowsAffected()
    fmt.Println(a) // 1
func ErrorCheck(err error) {
    if err != nil {
func PingDB(db *sql.DB) {
    err := db.Ping()


G:\GoLang\examples>go run go_example.go

Related Source Code Examples

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course