Golang - MySQL Insert Example

In this source code example, we show how to insert data into 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 a 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`)

Golang - MySQL Insert Struct Example

In this example, we will insert a single 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"

func main() {

    db, err := sql.Open("mysql", "root:root@tcp(")
    defer db.Close()

    if err != nil {

	sql := "INSERT INTO students(email, first_name, last_name) VALUES ('admin@gmail.com', 'admin','admin')"
    res, err := db.Exec(sql)

    if err != nil {

    lastId, err := res.LastInsertId()

    if err != nil {

    fmt.Printf("The last inserted row id: %d\n", lastId)


G:\GoLang\examples>go run go_example.go
The last inserted row id: 1

Related Source Code Examples