脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - Golang连接并操作PostgreSQL数据库基本操作

Golang连接并操作PostgreSQL数据库基本操作

2022-11-20 14:06天使手儿 Golang

PostgreSQL是常见的免费的大型关系型数据库,具有丰富的数据类型,也是软件项目常用的数据库之一,下面这篇文章主要给大家介绍了关于Golang连接并操作PostgreSQL数据库基本操作的相关资料,需要的朋友可以参考下

前言:

本篇文章对如何使用golang连接并操作postgre数据库进行了简要说明。文中使用到的主要工具:DBeaver21、VSCode,Golang1.17。

以用户,文章,评论三个表作为例子,下面是数据库建表sql:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
CREATE TABLE public.user_info (
    u_id serial4 NOT NULL,
    user_name varchar NULL,
    create_time date NULL,
    CONSTRAINT user_info_pk PRIMARY KEY (u_id)
);
CREATE TABLE public.user_info (
    u_id serial4 NOT NULL,
    user_name varchar NULL,
    create_time date NULL,
    CONSTRAINT user_info_pk PRIMARY KEY (u_id)
);
CREATE TABLE public."comment" (
    c_id serial4 NOT NULL,
    "content" varchar NULL,
    CONSTRAINT comment_pk PRIMARY KEY (c_id)
);

连接数据库

连接postgre数据库的驱动有很多,我们选用了github.com/lib/pq。下面看连接的方法。我们引入pq包时使用了_进行匿名加载,而不是直接使用驱动包。在对数据库的操作仍然是使用自带的sql包。另外,postgre默认使用的是public模式(schema),我们创建的表也是在这个模式下的。可以直接在数据库中修改默认模式或者在连接url中添加currentSchema=myschema来指定默认的模式,当然也可以在sql中使用myschema.TABLE来指定要访问的模式。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main
 
import (
    "database/sql"
    "fmt"
 
    _ "github.com/lib/pq"
)
 
var db *sql.DB
 
func DbOpen() {
    var err error
    //参数根据自己的数据库进行修改
    db, err = sql.Open("postgres", "host=localhost port=5432 user=angelhand password=2222 dbname=ahdb sslmode=disable")
    checkError(err)
    err = db.Ping()
    checkError(err)
}

sql.DB

需要注意的是,sql.DB并不是数据库连接,而是一个go中的一个数据结构:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
type DB struct {
    // Atomic access only. At top of struct to prevent mis-alignment
    // on 32-bit platforms. Of type time.Duration.
    waitDuration int64 // Total time waited for new connections.
 
    connector driver.Connector
    // numClosed is an atomic counter which represents a total number of
    // closed connections. Stmt.openStmt checks it before cleaning closed
    // connections in Stmt.css.
    numClosed uint64
 
    mu           sync.Mutex // protects following fields
    freeConn     []*driverConn
    connRequests map[uint64]chan connRequest
    nextRequest  uint64 // Next key to use in connRequests.
    numOpen      int    // number of opened and pending open connections
    // Used to signal the need for new connections
    // a goroutine running connectionOpener() reads on this chan and
    // maybeOpenNewConnections sends on the chan (one send per needed connection)
    // It is closed during db.Close(). The close tells the connectionOpener
    // goroutine to exit.
    openerCh          chan struct{}
    closed            bool
    dep               map[finalCloser]depSet
    lastPut           map[*driverConn]string // stacktrace of last conn's put; debug only
    maxIdleCount      int                    // zero means defaultMaxIdleConns; negative means 0
    maxOpen           int                    // <= 0 means unlimited
    maxLifetime       time.Duration          // maximum amount of time a connection may be reused
    maxIdleTime       time.Duration          // maximum amount of time a connection may be idle before being closed
    cleanerCh         chan struct{}
    waitCount         int64 // Total number of connections waited for.
    maxIdleClosed     int64 // Total number of connections closed due to idle count.
    maxIdleTimeClosed int64 // Total number of connections closed due to idle time.
    maxLifetimeClosed int64 // Total number of connections closed due to max connection lifetime limit.
 
    stop func() // stop cancels the connection opener.
}

在拿到sql.DB时并不会创建新的连接,而可以认为是拿到了一个数据库连接池,只有在执行数据库操作(如Ping()操作)时才会自动生成一个连接并连接数据库。在连接操作执行完毕后应该及时地释放。此处说的释放是指释放连接而不是sql.DB连接,通常来说一个sql.DB应该像全局变量一样长期保存,而不要在某一个小函数中都进行Open()Close()操作,否则会引起资源耗尽的问题。

增删改查

下面代码实现对数据简单的增删改查操作。

插入数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
func insert() {
    stmt, err := db.Prepare("INSERT INTO user_info(user_name,create_time) VALUES($1,$2)")
    if err != nil {
        panic(err)
    }
 
    res, err := stmt.Exec("ah", time.Now())
    if err != nil {
        panic(err)
    }
 
    fmt.Printf("res = %d", res)
}

使用Exec()函数后会返回一个sql.Result即上面的res变量接收到的返回值,它提供了LastInserId() (int64, error)RowsAffected() (int64, error)分别获取执行语句返回的对应的id和语句执行所影响的行数。

更新数据

?
1
2
3
4
5
6
7
8
9
10
11
12
func update() {
    stmt, err := db.Prepare("update user_info set user_name=$1 WHERE u_id=$2")
    if err != nil {
        panic(err)
    }
    res, err := stmt.Exec("angelhand", 1)
    if err != nil {
        panic(err)
    }
 
    fmt.Printf("res = %d", res)
}

查询数据

结构体如下:

?
1
2
3
4
5
type u struct {
    id          int
    user_name   string
    create_time time.Time
}

接下来是查询的代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func query() {
    rows, err := db.Query("select u_id, user_name, create_time from user_info where user_name=$1", "ah")
    if err != nil {
        panic(err)
 
    }
    //延迟关闭rows
    defer rows.Close()
 
    for rows.Next() {
        user := u{}
        err := rows.Scan(&user.id, &user.user_name, &user.create_time)
        if err != nil {
            panic(err)
        }
        fmt.Printf("id = %v, name = %v, time = %v\n", user.id, user.user_name, user.create_time)
    }
}

可以看到使用到的几个关键函数rows.Close()rows.Next()rows.Scan()。其中rows.Next()用来遍历从数据库中获取到的结果集,随用用rows.Scan()来将每一列结果赋给我们的结构体。

需要强调的是rows.Close()。每一个打开的rows都会占用系统资源,如果不能及时的释放那么会耗尽系统资源。defer语句类似于java中的finally,功能就是在函数结束前执行后边的语句。换句话说,在函数结束前不会执行后边的语句,因此在耗时长的函数中不建议使用这种方式释放rows连接。如果要在循环中重发查询和使用结果集,那么应该在处理完结果后显式调用rows.Close()

db.Query()实际上等于创建db.Prepare(),执行并关闭之三步操作。

还可以这样来查询单条记录:

err := db.Query("select u_id, user_name, create_time from user_info where user_name=$1", "ah").Scan(&user.user_name)

删除数据

?
1
2
3
4
5
6
7
8
9
10
11
12
func delete() {
    stmt, err := db.Prepare("delete from user_info where user_name=$1")
    if err != nil {
        panic(err)
    }
    res, err := stmt.Exec("angelhand")
    if err != nil {
        panic(err)
    }
 
    fmt.Printf("res = %d", res)
}

总结

到此这篇关于Golang连接并操作PostgreSQL数据库基本操作的文章就介绍到这了,更多相关Golang连接操作PostgreSQL内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_42893430/article/details/122072831

延伸 · 阅读

精彩推荐
  • GolangGoland编辑器设置选择范围背景色的操作

    Goland编辑器设置选择范围背景色的操作

    这篇文章主要介绍了Goland编辑器设置选择范围背景色的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    Jeffid9852021-02-24
  • Golang详解go语言中sort如何排序

    详解go语言中sort如何排序

    我们的代码业务中很多地方需要我们自己进行排序操作,本文主要介绍了详解go语言中sort如何排序,文中通过示例代码介绍的非常详细,具有一定的参考价...

    Zhan-LiZ11932022-09-05
  • Golang如何使用 Go 中的函数类型 (Function Types)?

    如何使用 Go 中的函数类型 (Function Types)?

    函数类型(function types)是一种很特殊的类型,它表示着所有拥有同样的入参类型和返回值类型的函数集合。...

    Go编程时光5272021-09-15
  • Golanggolang slice元素去重操作

    golang slice元素去重操作

    这篇文章主要介绍了golang slice元素去重操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    风格色10312021-06-11
  • GolangGo语言基础单元测试与性能测试示例详解

    Go语言基础单元测试与性能测试示例详解

    这篇文章主要为大家介绍了Go语言基础单元测试与性能测试示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助祝大家多多进步...

    枫少文7932021-12-05
  • GolangGo 通过结构struct实现接口interface的问题

    Go 通过结构struct实现接口interface的问题

    这篇文章主要介绍了Go 通过结构struct实现接口interface的问题,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要...

    踏雪无痕SS5322021-11-18
  • Golanggolang利用不到20行代码实现路由调度详解

    golang利用不到20行代码实现路由调度详解

    这篇文章主要给大家介绍了关于golang利用不到20行代码实现路由调度的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参...

    xialeistudio5002020-05-18
  • GolangGOLANG使用Context管理关联goroutine的方法

    GOLANG使用Context管理关联goroutine的方法

    这篇文章主要介绍了GOLANG使用Context管理关联goroutine的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋...

    winlin6182020-05-22