Golang连接PostgreSQL基本操作的实现

 更新时间:2024年02月26日 10:12:02   作者:天使手儿  
PostgreSQL是常见的免费的大型关系型数据库,本文主要介绍了Golang连接PostgreSQL基本操作的实现,具有一定的参考价值,感兴趣的可以了解一下

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

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

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来指定要访问的模式。

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中的一个数据结构:

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()操作,否则会引起资源耗尽的问题。

增删改查

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

插入数据

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和语句执行所影响的行数。

更新数据

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)
}

查询数据

结构体如下:

type u struct {
    id          int
    user_name   string
    create_time time.Time
}

接下来是查询的代码

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)

删除数据

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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

相关文章

  • go cron定时任务的基本使用讲解

    go cron定时任务的基本使用讲解

    这篇文章主要为大家介绍了gocron定时任务的基本使用讲解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • 详解Go语言设计模式之单例模式

    详解Go语言设计模式之单例模式

    单例模式很容易记住。就像名称一样,它只能提供对象的单一实例,保证一个类只有一个实例,并提供一个全局访问该实例的方法。本文就来聊聊Go语言中的单例模式,感兴趣的小伙伴可以了解一下
    2022-10-10
  • 一文带你全面掌握Go语言中的正则表达式

    一文带你全面掌握Go语言中的正则表达式

    正则表达式是一种强大的模式匹配工具,能够在文本中进行灵活的搜索和替换操作,本文将介绍 Golang 中的正则表达式语法,包括常用的匹配符号、模式修饰符以及示例应用,希望对大家有所帮助
    2023-05-05
  • Go 库性能分析工具pprof

    Go 库性能分析工具pprof

    这篇文章主要为大家介绍了Go 库性能分析工具pprof,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12
  • go语言LeetCode题解1030距离顺序排列矩阵单元格

    go语言LeetCode题解1030距离顺序排列矩阵单元格

    这篇文章主要为大家介绍了go语言LeetCode题解1030距离顺序排列矩阵单元格,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12
  • 如何使用Goland IDE go mod 方式构建项目

    如何使用Goland IDE go mod 方式构建项目

    这篇文章主要介绍了如何使用Goland IDE go mod 方式构建项目,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-10-10
  • Go 超时控制:context 与 timeout从实战到原理解析

    Go 超时控制:context 与 timeout从实战到原理解析

    本文主要讲解了Go语言中使用context进行超时控制的核心概念、使用方法、常见错误与坑以及底层实现原理,context用于管理生命周期,通过控制信号传播机制优雅地终止任务,示例展示了其在HTTP请求、goroutine控制、多层调用链中的应用,总结了常见错误并提供了最佳实践
    2026-05-05
  • Golang中Channel实战技巧与一些说明

    Golang中Channel实战技巧与一些说明

    channel是Go语言内建的first-class类型,也是Go语言与众不同的特性之一,下面这篇文章主要给大家介绍了关于Golang中Channel实战技巧与一些说明的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-11-11
  • 在 Go 语言中使用 regexp 包处理正则表达式的操作

    在 Go 语言中使用 regexp 包处理正则表达式的操作

    正则表达式是处理字符串时一个非常强大的工具,而 Go 语言的 regexp 包提供了简单而强大的接口来使用正则表达式,本文将介绍如何在 Go 中使用 regexp 包来编译和执行正则表达式,以及如何从文本中匹配和提取信息,感兴趣的朋友一起看看吧
    2023-12-12
  • Air实现Go程序实时热重载使用过程解析示例

    Air实现Go程序实时热重载使用过程解析示例

    这篇文章主要为大家介绍了Air实现Go程序实时热重载使用过程解析示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪
    2022-04-04

最新评论