2017年6月14日 星期三

Golang : Connect to MySQL




package main

import (
 "database/sql"
 "fmt"

 _ "github.com/Go-SQL-Driver/MySQL"
)

func main() {
 db, err := sql.Open("mysql", "go:rootroot@tcp(192.168.1.xxx:3306)/go?charset=utf8")
 if err != nil {
                fmt.Println("Panic: 1")
  panic(err)
 }

 //insert data
 stmt, err := db.Prepare("INSERT go SET firstname=?, lastname=?,age=?")

 if err != nil {
                fmt.Println("Panic: 2")
  panic(err)
 }

 res, err := stmt.Exec("new", "NAME", 12)
 if err != nil {
                fmt.Println("Panic: 3")
  panic(err)
 }

 fmt.Println(res)

 //update data
 stmt, err = db.Prepare("UPDATE go SET firstname=?, lastname=? WHERE age = ?")
 if err != nil {
                fmt.Println("Panic: 4")
  panic(err)
 }

 res, err = stmt.Exec("TESTUPDATE", "updatelastname", 12)
 if err != nil {
                fmt.Println("Panic: 5")
  panic(err)
 }

 affect, err := res.RowsAffected()
 if err != nil {
                fmt.Println("Panic: 6")
  panic(err)
 }

 fmt.Println(affect)
}

沒有留言:

張貼留言

© Mac Taylor, 歡迎自由轉貼。
Background Email Pattern by Toby Elliott
Since 2014