在進(jìn)行開發(fā)之前首先要使用git下載mysql的驅(qū)動(dòng)实蔽,github上面的mysql驅(qū)動(dòng)有好幾個(gè),我在這里選擇的https://github.com/go-sql-driver/mysql,
執(zhí)行命令:go get -u github.com/go-sql-driver/mysql
在正式開發(fā)之前先創(chuàng)建對(duì)應(yīng)的數(shù)據(jù)庫和表
CREATE TABLE `userinfo` (
`autid` INT(10) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(64) NULL DEFAULT NULL,
`departname` VARCHAR(64) NULL DEFAULT NULL,
`password` VARCHAR(64) NULL DEFAULT NULL,
`uid` VARCHAR(64) NULL DEFAULT NULL,
`created` DATE NULL DEFAULT NULL,
PRIMARY KEY (`uid`)
);
導(dǎo)入基本類庫
import (
"crypto/md5"
"database/sql"
"encoding/hex"
"fmt"
_ "github.com/go-sql-driver/mysql"
"strconv"
"time"
)
下面主要從增刪查改四個(gè)方面介紹go語言中mysql的使用
一舔痕、注冊(cè)數(shù)據(jù)庫驅(qū)動(dòng)
使用sql.Open()函數(shù)打開注冊(cè)一個(gè)注冊(cè)過的驅(qū)動(dòng),第一個(gè)參數(shù)是數(shù)據(jù)庫類型熟空,第二個(gè)參數(shù)是,第二個(gè)參數(shù)是DSN(Data Source Name)搞莺,它是go-sql-driver定義的一些數(shù)據(jù)庫鏈接和配置信息,DSN有以下格式:
user@unix(/path/to/socket)/dbname?charset=utf8
user:password@tcp(localhost:5555)/dbname?charset=utf8
user:password@/dbname
user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname
代碼如下:
const (
DB_Driver = "root:meddeex@tcp(127.0.0.1:3306)/medex?charset=utf8"
)
func OpenDB() (success bool, db *sql.DB) {
var isOpen bool
db, err := sql.Open("mysql", DB_Driver)
if err != nil {
isOpen = false
} else {
isOpen = true
}
CheckErr(err)
return isOpen, db
}
二息罗、插入
func insertToDB(db *sql.DB) {
uid := GetNowtimeMD5()
nowTimeStr := GetTime()
stmt, err := db.Prepare("insert userinfo set username=?,departname=?,created=?,password=?,uid=?")
CheckErr(err)
res, err := stmt.Exec("wangbiao", "研發(fā)中心", nowTimeStr, "123456", uid)
CheckErr(err)
id, err := res.LastInsertId()
CheckErr(err)
if err != nil {
fmt.Println("插入數(shù)據(jù)失敗")
} else {
fmt.Println("插入數(shù)據(jù)成功:", id)
}
}
三、查詢
func QueryFromDB(db *sql.DB) {
rows, err := db.Query("SELECT * FROM userinfo")
CheckErr(err)
if err != nil {
fmt.Println("error:", err)
} else {
}
for rows.Next() {
var uid string
var username string
var departmentname string
var created string
var password string
var autid string
CheckErr(err)
err = rows.Scan(&uid, &username, &departmentname, &created, &password, &autid)
fmt.Println(autid)
fmt.Println(username)
fmt.Println(departmentname)
fmt.Println(created)
fmt.Println(password)
fmt.Println(uid)
}
}
四才沧、更新
func UpdateDB(db *sql.DB, uid string) {
stmt, err := db.Prepare("update userinfo set username=? where uid=?")
CheckErr(err)
res, err := stmt.Exec("zhangqi", uid)
affect, err := res.RowsAffected()
fmt.Println("更新數(shù)據(jù):", affect)
CheckErr(err)
}
五迈喉、刪除
func DeleteFromDB(db *sql.DB, autid int) {
stmt, err := db.Prepare("delete from userinfo where autid=?")
CheckErr(err)
res, err := stmt.Exec(autid)
affect, err := res.RowsAffected()
fmt.Println("刪除數(shù)據(jù):", affect)
}
開發(fā)過程中用到的一些工具類方法
func CheckErr(err error) {
if err != nil {
panic(err)
fmt.Println("err:", err)
}
}
func GetTime() string {
const shortForm = "2006-01-02 15:04:05"
t := time.Now()
temp := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.Local)
str := temp.Format(shortForm)
fmt.Println(t)
return str
}
func GetMD5Hash(text string) string {
haser := md5.New()
haser.Write([]byte(text))
return hex.EncodeToString(haser.Sum(nil))
}
func GetNowtimeMD5() string {
t := time.Now()
timestamp := strconv.FormatInt(t.UTC().UnixNano(), 10)
return GetMD5Hash(timestamp)
}
調(diào)用
func main() {
opend, db := OpenDB()
if opend {
fmt.Println("open success")
} else {
fmt.Println("open faile:")
}
DeleteFromDB(db, 10)
//QueryFromDB(db)
//DeleteFromDB(db, 1)
//UpdateDB(db, 5)
//insertToDB(db)
//UpdateUID(db, 5)
//UpdateTime(db, 4)
}
寫在最后:
本篇文章主要介紹mysql在go語言開發(fā)中的基本使用,其實(shí)真正開發(fā)過程中還是主要使用orm相關(guān)第三方框架温圆,但是底層原理還是要學(xué)的挨摸。