Skip to content

Instantly share code, notes, and snippets.

@ascali
Forked from nakagami/simplest_mysql.go
Created November 15, 2021 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ascali/b44df060597fc743096ff62f51c9757e to your computer and use it in GitHub Desktop.
Save ascali/b44df060597fc743096ff62f51c9757e to your computer and use it in GitHub Desktop.
My first Go + mysql sample code. 1. go get github.com/go-sql-driver/mysql 2. mysql -e 'create database test_go;' 3. go run simplest_mysql.go
// Please crete database before go run this code
// ex) mysql -u root -e 'create database test_go;'
package main
import (
"os"
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main() {
user := "root"
password := ""
database := "test_go"
var n int
var s string
con, err := sql.Open("mysql", user+":"+password+"@/"+database)
_, err = con.Exec("create table t(n int, s varchar(256))")
if err != nil {
fmt.Println("Can't create table 't'")
os.Exit(1)
}
_, err = con.Exec("insert into t (n, s) values (1, 'foo')")
_, err = con.Exec("insert into t (n, s) values (?, ?)", 2, "bar")
fmt.Println("Select one row")
row := con.QueryRow("select n, s from t where n=1")
err = row.Scan(&n, &s)
fmt.Println(n, s) // 1, foo
row = con.QueryRow("select n, s from t where n=?", 2)
err = row.Scan(&n, &s)
fmt.Println(n, s) // 2, bar
fmt.Println("Select all rows")
rows, err := con.Query("select n, s from t")
for rows.Next() {
rows.Scan(&n, &s)
fmt.Println(n, s)
}
defer con.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment