首页  

GO操作Mysql     所属分类 go 浏览量 573
database/sql  
database/sql/driver 
没有提供官方的数据库驱动  需要导入第三方数据库驱动


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


sql包 内置连接池 自动创建和释放连接 
连接池大小  SetMaxdleConns


Db,err := sql.Open("maysql","root:密码@tcp(IP:端口)/数据库名")
if err != nil{
    panic(err.Error())       
}   

func Open(driverName,dataSourceName string)(*DB,error)

func (*DB)Ping() error
检查与数据库的连接是否有效


package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { fmt.Printf("hello,mysql \n") Db, err := sql.Open("mysql", "root:123456789abcd$@tcp(127.0.0.1:3306)/test") if err != nil { panic(err.Error()) } result := Db.Ping() fmt.Printf("ping result=%v \n", result) // CREATE TABLE users(id INT PRIMARY KEY ,username VARCHAR(32) NOT NULL UNIQUE,password VARCHAR(32) NOT NULL,email VARCHAR(64) ) AddUser(Db, 1, "admin", "123456", "admin@codefun007.xyz") AddUser(Db, 2, "tiger", "123", "tiger@codefun007.xyz") AddUser(Db, 3, "cat", "123", "cat@codefun007.xyz") // Exec result= nil,error=Error 1062: Duplicate entry '1' for key 'PRIMARY' // Exec result={0x1400016c090 0x140001222c0},error= nil user, _ := GetUserById(Db, 1) fmt.Printf("user=%v \n", user) fmt.Printf("id=%v,name=%v \n", user.Id, user.UserName) users, _ := GetAllUsers(Db) fmt.Printf("all users=%v \n", users) for index, value := range users { fmt.Printf("users[%v]=%v \n", index, value) } fmt.Printf("done") } func AddUser(Db *sql.DB, id int, name string, password string, email string) error { sql := "insert into users(id,username,password,email) values(?,?,?,?)" sqlPrepare, err := Db.Prepare(sql) if err != nil { return err } result, execError := sqlPrepare.Exec(id, name, password, email) fmt.Printf("Exec result=%v,error=%v \n", result, execError) return nil } type User struct { Id int UserName string Password string Email string } func GetUserById(Db *sql.DB, id int) (u *User, err error) { str := "select id,username,password,email from users where id = ?" strTmt, err := Db.Prepare(str) row := strTmt.QueryRow(id) var userId int var username string var password string var email string err = row.Scan(&userId, &username, &password, &email) if err != nil { return nil, err } user := &User{ Id: userId, UserName: username, Password: password, Email: email, } return user, err } func GetAllUsers(Db *sql.DB) (userSlice []*User, err error) { str := "select * from users" rows, err := Db.Query(str) var id int var username string var password string var email string for rows.Next() { err = rows.Scan(&id, &username, &password, &email) user := &User{ Id: id, UserName: username, Password: password, Email: email, } userSlice = append(userSlice, user) } return }
完整代码 https://gitee.com/dyyx/hellocode/blob/master/demo/go/gomysql/main.go

上一篇     下一篇
Go依赖管理 和 Go module使用

MAC M1 芯片

go rest api server 及 go mod 实战

余杭护国山

职场暗语

GO 快速教程