Go实战--go语言操作PostgreSQL数据库(github.com/lib/pq)

原文地址:https://blog.csdn.net/wangshubo1989/article/details/77478838?locationNum=3&fps=1

生命不止,继续 Go go go !!!

之前关于golang操作数据库的博客:

Go实战–go语言操作MySQL数据库(go-sql-driver/mysql)

Go实战–go语言操作sqlite数据库(The way to go)

Go实战–golang中使用MongoDB(mgo)

Go实战–golang中使用redis(redigo和go-redis/redis)

今天跟大家分享golang中使用PostgreSQL数据库。
这里写图片描述

何为PostgreSQL

官网
https://www.postgresql.org/

PostgreSQL is a powerful, open source object-relational database system.
PostgreSQL是一个功能强大的开源对象关系数据库管理系统(ORDBMS)。 用于安全地存储数据; 支持最佳做法,并允许在处理请求时检索它们。

特点

  • PostgreSQL可在所有主要操作系统(即Linux,UNIX(AIX,BSD,HP-UX,SGI IRIX,Mac OS X,Solaris,Tru64)和Windows等)上运行

  • PostgreSQL支持文本,图像,声音和视频,并包括用于C/C++,Java,Perl,Python,Ruby,Tcl和开放数据库连接(ODBC)的编程接口

  • PostgreSQL支持SQL的许多功能,例如复杂SQL查询,SQL子选择,外键,触发器,视图,事务,多进程并发控制(MVCC),流式复制(9.0),热备(9.0))

  • 在PostgreSQL中,表可以设置为从“父”表继承其特征

  • 可以安装多个扩展以向PostgreSQL添加附加功能

PostgreSQL 与 MySQL 相比,优势何在?
知乎上有大神们的讨论,可以看一看:https://www.zhihu.com/question/20010554

Windows下安装PostgreSQL

下载
https://www.postgresql.org/download/windows/

跳转到https://www.enterprisedb.com/downloads/postgres-postgresql-downloads#windows
根据自己的操作系统下载,例如我选择:
PostgreSQL 9.6.4
Windows x86-64

下载速度不是很快,稍安勿躁。

安装
下一步,选择安装文件夹,选择数据所在位置,填写密码,端口号,选择运行时语言环境等。
默默等待安装。

使用pgAdmin

打开pgAdmin,要输入之前设置的密码
这里写图片描述

创建数据库
在Databases(1)上右键,Create, Database
这里写图片描述

删除数据库
这里写图片描述

创建表
这里写图片描述
这里写图片描述

插入数据
这里写图片描述
这里写图片描述

PS:上面插入数据报错采用如下格式,并注意创建表时设置数据长度

INSERT INTO public.student( id, name) VALUES (4, '{wang}');

使用SQL Shell(psql)

创建数据库

create database name;
  
  
  • 1

这里写图片描述

删除数据库

drop database name;
  
  
  • 1

如果出现错误的话,请先断开其他对该数据库的连接。
这里写图片描述

创建表


CREATE TABLE public.student
(
    id integer,
    name character(1)[] COLLATE pg_catalog."default"
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE public.student
    OWNER to postgres;
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

插入数据

INSERT INTO public.teacher(
    id, age)
    VALUES (2, 34);
  
  
  • 1
  • 2
  • 3

查询

SELECT * FROM public.teacher;
  
  
  • 1

Go中使用PostgreSQL

github.com/lib/pq
Pure Go Postgres driver for database/sql

连接

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/lib/pq"
)

const (
    host     = "localhost"
    port     = 5432
    user     = "postgres"
    password = "your_password"
    dbname   = "test"
)

func main() {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, dbname)
    db, err := sql.Open("postgres", psqlInfo)
    if err != nil {
        panic(err)
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err)
    }

    fmt.Println("Successfully connected!")
}

  
  
  • 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

插入

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/lib/pq"
)

const (
    host     = "localhost"
    port     = 5432
    user     = "postgres"
    password = "wangshubo123"
    dbname   = "test"
)

type Teacher struct {
    ID  int
    Age int
}

func main() {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, dbname)
    db, err := sql.Open("postgres", psqlInfo)
    if err != nil {
        panic(err)
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err)
    }

    fmt.Println("Successfully connected!")

    sqlStatement := `
INSERT INTO teacher (id, age)  
VALUES ($1, $2)  
RETURNING id`
    id := 3
    err = db.QueryRow(sqlStatement, 3, 19).Scan(&id)
    if err != nil {
        panic(err)
    }
    fmt.Println("New record ID is:", id)
}

  
  
  • 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
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

再运行一次,错误:panic: pq: 重复键违反唯一约束”teacher_pkey”

查询

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/lib/pq"
)

const (
    host     = "localhost"
    port     = 5432
    user     = "postgres"
    password = "wangshubo123"
    dbname   = "test"
)

type Teacher struct {
    ID  int
    Age int
}

func main() {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, dbname)
    db, err := sql.Open("postgres", psqlInfo)
    if err != nil {
        panic(err)
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err)
    }

    fmt.Println("Successfully connected!")

    sqlStatement := `SELECT * FROM teacher WHERE id=$1;`
    var teacher Teacher
    row := db.QueryRow(sqlStatement, 1)
    err = row.Scan(&teacher.ID, &teacher.Age)
    switch err {
    case sql.ErrNoRows:
        fmt.Println("No rows were returned!")
        return
    case nil:
        fmt.Println(teacher)
    default:
        panic(err)
    }
}

  
  
  • 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
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

这里写图片描述

猜你喜欢

转载自blog.csdn.net/dodod2012/article/details/87799742