go mysql 基礎操作 (CURD)

nonespace發表於2018-09-07

資料庫資料結構

這裡寫程式碼片

##程式碼演示

package main

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"fmt"
)

func main() {
	db, err := sql.Open("mysql", "root:LZX1992-:=@tcp(58.87.92.197:3306)/my_blog?charset=utf8")
	if err != nil {
		panic(err)

	}
	Get(db)
	Insert(db)
	update(db ,"葫蘆公司",96)
	del(db, 96)
}

func Get(db *sql.DB) {

	rows, err := db.Query("select  * from class where class_id = ?", 3)
	if err != nil {
		panic(err)

	}
	arr := []map[string]interface{}{}
	for rows.Next() {
		var m = make(map[string]interface{})
		var classId int
		var className string
		err = rows.Scan(&classId, &className)
		m["class_name"] = className
		m["class_id"] = classId
		arr = append(arr, m)

	}

	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("b->", arr)
}

func Insert(db *sql.DB) {
	stmt, err := db.Prepare("insert class set class_name=?")
	res, err := stmt.Exec("Golang")
	//row,err := res.RowsAffected()受影響行數
	classId, err := res.LastInsertId() //返回最後一個ID
	if err != nil {
		panic(err)
		return
	}
	fmt.Println(classId)

}

func update(db *sql.DB, name string, id int) {
	stmt, err := db.Prepare("update class set class_name = ? where class_id=?")
	res, err := stmt.Exec(name, id)
	row, err := res.RowsAffected() //受影響行數
	if err != nil {
		panic(err)
		return
	}
	fmt.Println(row)

}

func del(db *sql.DB, id int) {
	stmt, err := db.Prepare("DELETE FROM class WHERE class_id =?")
	res, err := stmt.Exec(id)
	row, err := res.RowsAffected() //受影響行數
	if err != nil {
		panic(err)
		return
	}
	fmt.Println(row)
}

複製程式碼

相關文章