目录结构

点击查看原图

 

@GOPATH

点击查看原图

 

 

CREATE TABLE `userinfo` (

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(20) NOT NULL DEFAULT '',

  `uid` int(10) unsigned NOT NULL DEFAULT '0',

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8


 

1.go

package main
 
import (
	"conf"
	"fmt"
	// 或者
	// myDbConf "conf"
)
 
func main() {
	opend, db := conf.OpenDB()
	//opend, db := myDbConf.OpenDB()
 
	fmt.Println(db)
	if opend {
		fmt.Println("open success")
	} else {
		fmt.Println("open faile:")
	}
	// DeleteFromDB(db, 10)
	//QueryFromDB(db)
	//DeleteFromDB(db, 1)
	//UpdateDB(db, 5)
	conf.InsertToDB(db)
	//myDbConf.InsertToDB(db)
 
	//UpdateUID(db, 5)T
	//UpdateTime(db, 4)
 
}

 
 
 
dbConf.go
package dbConf
 
import (
	"crypto/md5"
	"database/sql"
	"encoding/hex"
	"fmt"
	"strconv"
	"time"
 
	_ "github.com/go-sql-driver/mysql"
)
 
const (
	DB_Driver = "root:root@tcp(127.0.0.1:3306)/test?charset=utf8"
)
 
func OpenDB() (success bool, db *sql.DB) {
	var isOpen bool
	db, err := sql.Open("mysql", DB_Driver)
	// fmt.Println(db)
	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 name=?,uid=?")
	CheckErr(err)
	res, err := stmt.Exec("wangbiao", uid)
	CheckErr(err)
	id, err := res.LastInsertId()
	CheckErr(err)
	if err != nil {
		fmt.Println("插入数据失败")
	} else {
		fmt.Println("插入数据成功:", 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 name string
 
		CheckErr(err)
		err = rows.Scan(&uid, &name)
		fmt.Println(name)
		fmt.Println(uid)
	}
}
 
func UpdateDB(db *sql.DB, uid string) {
	stmt, err := db.Prepare("update userinfo set name=? where uid=?")
	CheckErr(err)
	res, err := stmt.Exec("zhangqi", uid)
	affect, err := res.RowsAffected()
	fmt.Println("更新数据:", affect)
	CheckErr(err)
}
func DeleteFromDB(db *sql.DB, id int) {
	stmt, err := db.Prepare("delete from userinfo where id=?")
	CheckErr(err)
	res, err := stmt.Exec(id)
	affect, err := res.RowsAffected()
	fmt.Println("删除数据:", affect)
}
 
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)
}
 mysql.zip

 

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权