Sunday 18 October 2020

go web app 3 mysql

//cmd - install mysql driver

C:\Users\bob\golang2>go get -u github.com/go-sql-driver/mysql

//cmd - insert

C:\Users\bob\golang2>go run main.go
Go MySQL Tutorial
Successfully Connected to MySQL database
Successfully inserted into table1

names inserted into mysql table

 // cmd - select

C:\Users\bob\golang2>go run main.go
Go MySQL Tutorial
Successfully Connected to MySQL database
Bob
Jack
Sam

//main.go

package main

import (
"database/sql"
"fmt"

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

func main() {
fmt.Println("Go MySQL Tutorial")

db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/testdb")

if err != nil {
panic(err.Error())
}

defer db.Close()

fmt.Println("Successfully Connected to MySQL database")

/*
insert, err := db.Query("INSERT INTO table1 (name) VALUES('Bob'), ('Jack'), ('Sam')")

if err != nil {
panic(err.Error())
}

defer insert.Close()

fmt.Println("Successfully inserted into table1")
*/

results, err := db.Query("SELECT name FROM table1")

if err != nil {
panic(err.Error())
}

for results.Next() {
name := ""

err = results.Scan(&name)

if err != nil {
panic(err.Error())
}

fmt.Println(name)
}
}

No comments:

Post a Comment