gomysqlhtml
gomysql是基於go-sql-driver基礎上開發的orm,這是一個輕量級的庫。它會使數據庫的增刪改查變得很是容易。固然也是測試開發版,會一直優化和更新!請時刻關注咱們git
go get github.com/go-sql-driver/mysql go get github.com/widuu/goini go get github.com/widuu/gomysql
mysql :github.com/Go-SQL-Driver/MySQLgithub
goini :github.com/widuu/goinisql
設置配置文件數據庫
[database] username = mysql username password = mysql password hostname = mysql host charset = mysql charset database = database name port = mysql port
初始化配置測試
c, _ := gomysql.SetConfig("./conf/conf.ini") //根據配置文件,鏈接數據庫
查詢數據優化
t := c.SetTable("user") //設置要處理的表名 data := t.FindOne() //查詢表的一條數據,返回map[int]map[string]string格式 gomysql.Print(data) //打印數據信息,返回以下截圖的數據格式
data := t.Fileds("id", "password", "username").Where("id =12").FindOne() //Fileds 查詢字段,Where where條件FindOne()查詢一條 //limit sql中的limit OrderBy sql中查詢的OrderBy data = c.SetTable("user").Fileds("id", "password", "username").Where("id>1").Limit(1, 5).OrderBy("id Desc").FindAll() data = t.FindAll() //查詢全部數據,其中OrderBy() Limit() Where() Fileds()等設置條件 gomysql.Print(data) //查詢的數據均可以用Print()方法友好打印出來信息
添加數據網站
var value = make(map[string]interface{}) //設置map存儲數據,map[key]value value["password"] = "mima3" value["username"] = "xiaowei" value["id"] = 10 t := c.SetTable("user") //設置增長的數據表 t.SetPk("id") //設置主鍵自增的字段名稱 i,err := t.Insert(value) // 插入數據,返回增長個數和錯誤信息。返回最後增加的id和錯誤信息
修改數據ui
var value = make(map[string]interface{}) value["password"] = "mima3" value["username"] = "xiaowei" n, err := c.SetTable("user").Where("id =5").Update(value) //設置表,條件和修改的內容,返回影響條數和錯誤信息
刪除數據
n, err := c.SetTable("user").Delete("id = 6") //設置刪除的表和數據,返回影響條數和錯誤信息
關聯操做
INNER JOIN
t := c.SetTable("user") //下面至關於sql語句,打印出是Select user.id,data.keywords,user.username,user.password from user INNER JOIN data ON user.id = data.id data := t.Fileds("user.id", "data.keywords", "user.username", "user.password").Join("data", "user.id = data.id").FindAll() fmt.Println(data)
LEFT JOIN
t.Fileds("user.id", "data.keywords", "user.username", "user.password").LeftJoin("data", "user.id = data.id").FindAll() fmt.Println(data)
RIGHT JOIN
t.Fileds("user.id", "data.keywords", "user.username", "user.password").RightJoin("data", "user.id = data.id").FindAll() fmt.Println(data)
FULL JOIN
data := t.Fileds("user.id", "data.keywords", "user.username", "user.password").RightJoin("data", "user.id = data.id").FindAll() fmt.Println(data)
自定義sql語句
// Query()方法 是自定義sql語句的
insert類型的數據
n := t.Query("INSERT INTO user (`username`,`password`) VALUES ('xiaoweitest','xiaowei')") //返回最後增加的id
update|delete
//update n := c.Query("update user set username='ceshishenma' where id =17 ") fmt.Println(n) //1 返回受影響行數 //delete n := c.Query("delete from user where id=16 ") fmt.Println(n) //1 返回受影響行數
select
data := c.Query("select username,password from user") fmt.Println(data) //返回map[int]map[string]string 結構的全部數據
關閉數據庫
c.DbClose() //關閉數據庫