泡面师

  • 首页
  • 记录
好记性不如烂笔头
  1. 首页
  2. 记录
  3. golang
  4. 正文

golang使用mysql连接池

2021-05-25 2978点热度 0人点赞 0条评论

安装

go get  github.com/go-sql-driver/mysql

初始化

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

var db, _ = sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/testmysql")

func init(){
    db.SetMaxOpenConns(threadNum)
    db.SetMaxIdleConns(threadNum / 2)
}

查询

rows, err := db.Query("select id,title from xx_news where id = ?", 123)
if err != nil {
    fmt.Println(err)
    return
}
defer rows.Close()
for rows.Next() {
    var (
        id        int64
        title string
    )
    if err = rows.Scan(&id, &title); err != nil {
        fmt.Println(err)
        return
    }

    fmt.Printf("%v,%v \n", id, title)
}

插入

stmt, err := db.Prepare(`INSERT INTO xx_news SET title = ?`)
if err != nil {
    fmt.Println(err)
}
res, err1 := stmt.Exec("测试标题")

if err1 != nil {
    fmt.Println(err1)
}
fmt.Println(res.LastInsertId)

更新

stmt, err := db.Prepare(`UPDATE xx_news SET title = ? WHERE id = ?`)
if err != nil {
    fmt.Println(err)
}
res, err1 := stmt.Exec("测试标题",123)
if err1 != nil {
    fmt.Println(err1)
}

fmt.Println(res)
标签: golang mysql
最后更新:2021-05-25

泡面师

这个人很懒,什么都没留下

点赞
< 上一篇

文章评论

取消回复

COPYRIGHT © 2024 泡面师. ALL RIGHTS RESERVED.

THEME KRATOS MADE BY VTROIS