Golang - MySQL Select Example

In this source code example, we show how to select or retrieve data from 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` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `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 select data from a database.

Golang - MySQL Insert Example

Golang MySQL Select Example

In this example, we will retrieve or select data from the students table.

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

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/go-sql-driver/mysql"
)

type Student struct {
    Id         int
    Email       string
    First_Name string
	Last_Name string
}

func main() {

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

    if err != nil {
        log.Fatal(err)
    }

    res, err := db.Query("SELECT * FROM students")

    defer res.Close()

    if err != nil {
        log.Fatal(err)
    }

    for res.Next() {

        var student Student
        err := res.Scan(&student.Id, &student.Email, &student.First_Name, &student.Last_Name)

        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("%v\n", student)
    }
}

Output:

G:\GoLang\examples>go run go_example.go
{1 admin@gmail.com admin admin}

Related Source Code Examples


Comments