Golang 學習系列第四天:運算元據庫 PostgreSQL

dongguangming發表於2020-07-18

Golang學習系列第三天:學習陣列、切片、Map、結構體、指標、函式、介面型別、channel通道,今天學習golang運算元據庫,以PostgreSQL為例。

可以參考PostgreSQL官網www.postgresql.org/download/linux/...安裝該資料庫

特別需要說明的是,安裝完成後,自動建立了一個名為postgres的使用者,預設密碼為空;同時也自動建立了一個名字叫postgres的資料庫。

0.1、修改預設生成的資料庫使用者postgres的密碼。

修改PostgreSQL使用者密碼

把密碼設定為12345678.

0.2 建立示例資料庫

測試資料庫名可以自取,

示例資料庫

然後建一張測試表讓golang使用

CREATE TABLE users (
    id serial PRIMARY KEY,
    email VARCHAR (355) UNIQUE NOT NULL,
    password VARCHAR (50) NOT NULL
);

insert into users(id,email,password) values(1,'1056764180@qq,com','12345678');
insert into users(id,email,password) values(2,'10567@qq,com','1234567890');
insert into users(id,email,password) values(3,'10567567@qq,com','12345678908');

0.3 開啟遠端訪問

由於資料庫和應用程式不在同一機器上,故資料庫要開啟遠端訪問功能

修改配置檔案,即

vim /var/lib/pgsql/12/data/postgresql.conf

找到listen_adderess配置項設為*

繼續修改另一配置檔案,即

vim /var/lib/pgsql/12/data/pg_hba.conf

在# IPv4 local connections:處追加客戶端的連線資訊

重啟postgresql服務

systemctl restart postgresql-12

最後客戶端測試連線

連線資料庫會使用第三方驅動包,由於牆的緣故,可以先設定一下代理

go env -w GO111MODULE=on
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct

就以基本的增刪改查資料,記錄如何使用go運算元據庫

1. 1 Select查詢資料

新建postgres.go專案,鍵入以下測試連線資料庫的程式碼

package main

import (
    "database/sql"
    "fmt"
    "log"
    _ "github.com/lib/pq"
    //_ "github.com/bmizerany/pq"

)

const (
    // TODO fill this in directly or through environment variable
    // Build a DSN e.g. postgres://username:password@url.com:5432/dbName
    DB_DSN = "postgres://postgres:12345678@192.168.8.200:5432/douyin?sslmode=disable"
)

type User struct {
    ID       int
    Email    string
    Password string
}

func main() {

    // Create DB pool
    //db, err := sql.Open("postgres", "host=192.168.8.200 port=5432 user=postgres password=12345678 dbname=douyin sslmode=disable")
    db, err := sql.Open("postgres",DB_DSN)
        if err != nil {
        log.Fatal("Failed to open a DB connection: ", err)
    }
    defer db.Close()

    // Create an empty user and make the sql query (using $1 for the parameter)
    var myUser User
    userSql := "SELECT id, email, password FROM users WHERE id = $1"

    err = db.QueryRow(userSql, 1).Scan(&myUser.ID, &myUser.Email, &myUser.Password)
    if err != nil {
        log.Fatal("Failed to execute query: ", err)
    }

    fmt.Printf("你好 郵箱:%s, 密碼:%s,  歡迎回來!\n", myUser.Email, myUser.Password)
}

然後建立一個模組依賴檔案

go mod init  pluginModel

安裝具體的依賴包

go get github.com/lib/pq

最後執行測試程式碼

[root@master goworkspace]# go run postgres.go

從資料庫查詢id等於1的記錄,如圖

和資料庫裡的資料是對應的

1.2 增加資料

接上1.1示例程式碼,稍作更改即可,檔案命名為postgres-create.go

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq"
        //_ "github.com/bmizerany/pq"

)

const (
    // TODO fill this in directly or through environment variable
    // Build a DSN e.g. postgres://username:password@url.com:5432/dbName
    DB_DSN = "postgres://postgres:12345678@192.168.8.200:5432/douyin?sslmode=disable"
)

type User struct {
    ID       int
    Email    string
    Password string
}

func main() {
    // Create DB pool
    //db, err := sql.Open("postgres", "host=192.168.8.200 port=5432 user=postgres 
    password=12345678 dbname=douyin sslmode=disable")
    db, err := sql.Open("postgres",DB_DSN)
        if err != nil {
        log.Fatal("Failed to open a DB connection: ", err)
    }
    defer db.Close()

    //建立一個使用者,預要插入到資料庫裡
    var user User = User{ID:4,Email:"110@qq.com",Password:"1234567890"}
    //執行插入操作
    _, err = db.Exec("INSERT INTO users (id,email,password) VALUES($1,$2,$3)", 
    user.ID,user.Email,user.Password)
    if err != nil {
        log.Fatal(err)
    }
    //列印日誌
    log.Printf("create ok!!!")

    //測試資料是否插入成功,執行具體的查詢語句
    var myUser User
    userSql := "SELECT id, email, password FROM users WHERE id = $1"

    //設定查詢引數為4,即建立資料時的ID值
    err = db.QueryRow(userSql, 4).Scan(&myUser.ID, &myUser.Email, 
    &myUser.Password)
    if err != nil {
        log.Fatal("Failed to execute query: ", err)
    }

    //輸出查詢結果
    fmt.Printf("hello email: %s, password: %s, welcome back!\n", 
    myUser.Email,myUser.Password)

}

執行程式程式碼,輸出結果

1.3 update修改資料

接上1.2示例程式碼,稍作更改即可,檔案命名為postgres-update.go

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq"
        //_ "github.com/bmizerany/pq"

)

const (
    // TODO fill this in directly or through environment variable
    // Build a DSN e.g. postgres://username:password@url.com:5432/dbName
    DB_DSN = "postgres://postgres:12345678@192.168.8.200:5432/douyin?sslmode=disable"
)

type User struct {
    ID       int
    Email    string
    Password string
}

func main() {
    // Create DB pool
    //db, err := sql.Open("postgres", "host=192.168.8.200 port=5432 user=postgres 
    password=12345678 dbname=douyin sslmode=disable")
    db, err := sql.Open("postgres",DB_DSN)
        if err != nil {
        log.Fatal("Failed to open a DB connection: ", err)
    }
    defer db.Close()

    //建立一個使用者,預要通過主鍵更改到資料庫裡
    var user User = User{ID:4,Email:"dong@qq.com",Password:"abcdedf120"}
    //執行更改操作
    _, err = db.Exec("UPDATE  users SET email=$1, password=$2 where id=$3", user.Email,user.Password,user.ID)
    if err != nil {
        log.Fatal(err)
    }
    //列印日誌
    log.Printf("update ok!!!")

    //測試資料是否更改成功,執行具體的查詢語句
    var myUser User
    userSql := "SELECT id, email, password FROM users WHERE id = $1"

    //設定查詢引數為4,即要更改資料的ID值
    err = db.QueryRow(userSql, 4).Scan(&myUser.ID, &myUser.Email, 
    &myUser.Password)
    if err != nil {
        log.Fatal("Failed to execute query: ", err)
    }

    //輸出查詢結果
    fmt.Printf("hello email: %s, password: %s, welcome back!\n", 
    myUser.Email,myUser.Password)

}

執行程式程式碼,輸出結果

1.4 delete刪除資料記錄

接上1.3示例程式碼,稍作更改即可,檔案命名為postgres-delete.go

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq"
        //_ "github.com/bmizerany/pq"

)

const (
    // TODO fill this in directly or through environment variable
    // Build a DSN e.g. postgres://username:password@url.com:5432/dbName
    DB_DSN = "postgres://postgres:12345678@192.168.8.200:5432/douyin?sslmode=disable"
)

type User struct {
    ID       int
    Email    string
    Password string
}

func main() {
    // Create DB pool
    //db, err := sql.Open("postgres", "host=192.168.8.200 port=5432 user=postgres 
    password=12345678 dbname=douyin sslmode=disable")
    db, err := sql.Open("postgres",DB_DSN)
        if err != nil {
        log.Fatal("Failed to open a DB connection: ", err)
    }
    defer db.Close()

    //執行更改操作
    _, err = db.Exec("DELETE FROM  users  where id=$1", 4)
    if err != nil {
        log.Fatal(err)
    }
    //列印日誌
    log.Printf("delete ok!!!")

    //測試資料是否更改成功,執行具體的查詢語句
    var myUser User
    userSql := "SELECT id, email, password FROM users WHERE id = $1"

    //設定查詢引數為4,即要更改資料的ID值
    err = db.QueryRow(userSql, 4).Scan(&myUser.ID, &myUser.Email, 
    &myUser.Password)
    if err != nil {
        log.Fatal("Failed to execute query: ", err)
    }

    //輸出查詢結果
    fmt.Printf("hello email: %s, password: %s, welcome back!\n", 
    myUser.Email,myUser.Password)
}

執行以上程式程式碼,執行輸出結果

至此到這裡關於golang運算元據庫postgresql就告一段落了,收工。

程式碼已上傳到github:github.com/dongguangming/golang-le...

注:由於我沒有用視覺化程式設計工具,是用vi編寫的go程式碼,請你們自行排版其結構。

參考:

  1. Postgresql 密碼設定 www.mamicode.com/info-detail-197754...

  2. golang連線postgresql資料庫 msd.misuland.com/pd/31814385785970...

  3. cannot find module providing package github.com/xxx: working directory is not part of a module www.sunzhongwei.com/cannot-find-mo...

  4. SSL is not enabled on the server stackoverflow.com/questions/219591...

  5. Resolve “FATAL:no pg_hba.conf entry for host” Error when you Connect from PGAdmin4 www.cisco.com/c/en/us/support/docs...

  6. Connect to PostgreSQL and Run a Query golangcode.com/postgresql-connect-...

  7. golang postgresql CRUD www.cnblogs.com/ibgo/p/6010245.htm...

本作品採用《CC 協議》,轉載必須註明作者和本文連結

人生,不應設限

相關文章