Go 操作 PostgreSQL
Go PostgreSQL About 1,193 words下载驱动
使用github.com/lib/pq
驱动:https://github.com/lib/pq
go get -u github.com/lib/pq
链接数据库
import (
"database/sql"
"fmt"
"log"
"time"
_ "github.com/lib/pq"
)
var pg *sql.DB
func init() {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "127.0.0.1", 5432, "z-blog", "", "z-blog")
db, err := sql.Open("postgres", psqlInfo)
//connStr := "postgres://testuser:testpwd@127.0.0.1/testdb?sslmode=verify-full"
//db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
pg = db
pg.SetConnMaxLifetime(time.Minute * 3)
pg.SetMaxOpenConns(10)
pg.SetMaxIdleConns(10)
err = pg.Ping()
if err != nil {
log.Fatal(err)
}
}
func main() {
defer pg.Close()
// TODO
}
查询
占位符:$1
...$n
func queryForObject() {
var (
id int
name string
)
row := db.QueryRow("select id, name from tb_user where id = $1 limit 1", 1)
err := row.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
log.Println("queryForObject#", id, name)
}
其余操作
其余操作与database/sql
包下相同。
驱动列表
Views: 4,412 · Posted: 2020-11-10
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...