Golang - 数据库操作

1. 下载安装包

go get github.com/Go-SQL-Driver/MySQL
go install github.com/Go-SQL-Driver/MySQL

2. 连接池

This essentially means that, every time you query your database, you are using a connection from a pool of connections that have been set up on application startup. These connections are reused, time and time again, and this subsequently means you aren’t creating and destroying a new connection every time you perform a query.

3. 数据库操作

连接 - db是connection

db, err := sql.Open("mysql", "<username>:<password>@tcp(127.0.0.1:3306)/<yourdatabase>")
if err != nil {
    panic(err.Error())
}
defer db.Close()
// here you can use the connection, it will be closed when function returns

插入数据

insert, err := db.Query("insert into t1 values(2, 'here')")
if err != nil {
    panic(err.Error())
}
defer insert.Close()

 搜索

- struct. 如果外部包导入失败,尝试用tag := Tag{ID: , Name:}导入一次再改成var tag Tag...

type Tag struct {
    ID   int 
    Name string
}

- 导入

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

- 程序

results, err := db.Query("Select * from t1")
if err != nil {
    panic(err.Error())
}
for results.Next() {
    //tag := Tag{ID: 1, Name: "hhh"}
    var tag Tag
    err = results.Scan(&tag.ID, &tag.Name)
    if err != nil {
        panic(err.Error())
    }
    log.Printf(tag.Name)
}

-----------From Others
items := make([]*SomeStruct, 0, 10) var ida, idb uint for rows.Next() { err = rows.Scan(&ida, &idb) if err != nil { /* error handling */} items = append(items, &SomeStruct{ida, idb}) }

- QueryRow

QueryRow executes a query that is expected to return at most one row. QueryRow calls Query, and then wraps the results in an sql.Row. 

var tag Tag
// Execute the query
err = db.QueryRow("SELECT * FROM t1 where num = ?", 1).Scan(&tag.ID, &tag.Name)
if err != nil {
    panic(err.Error())
}

log.Println(tag.ID)
log.Println(tag.Name)

 Prepare Statement (Example)

stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
res, err := stmt.Exec("zhja", "研发", "2016-06-17")

获取最后一个自增ID

id, err := res.LastInsertId()

猜你喜欢

转载自www.cnblogs.com/GW977/p/10793886.html