使用 go 连接和查询postgresql

Content:

使用go来查询postgressql

Example:

/*
  使用go查询postgres 数据库
  Mousse 2018.8.22.00-->KM
*/
package main

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


const (
    host     = "localhost"
    port     = 5432
    user     = "root"
    password = "123456"
    dbname   = "test"
)


type DeviceInfo struct {
    DeviceName     string
    DeviceID       string
    DeviceUsername string
    Token          string
}


func Connect()(*sql.DB){
    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)
    }
    err = db.Ping()
    if err != nil {
        panic(err)
    }
    fmt.Println("Successfully connected!")
    return db
}


func QuerySingle(db *sql.DB) DeviceInfo{
    var device DeviceInfo
    sqlStatement := `SELECT "deviceName", "deviceID", "deviceUsername", token FROM devices WHERE id = 5 `
    row := db.QueryRow(sqlStatement)
    row.Scan(&device.DeviceID, &device.DeviceUsername, &device.Token, &device.DeviceName)
    return device
}


func QueryMultiple(db *sql.DB) []DeviceInfo{
    var device DeviceInfo
    sqlStatement := `SELECT "deviceName", "deviceID", "deviceUsername", 
                     token FROM devices LIMIT 10`
    rows, err := db.Query(sqlStatement)
    if err != nil {
        panic(err)
    }
    defer rows.Close()
    var deviceSlice []DeviceInfo
    for rows.Next(){
        rows.Scan(&device.DeviceID, &device.DeviceUsername, &device.Token, &device.DeviceName)
        deviceSlice = append(deviceSlice, device)
    }
    return deviceSlice
}


func main() {
    // 连接数据库
    db := Connect()
    // 查询单个
    result := QuerySingle(db)
    fmt.Println("query result\n", result)
    // 查询多条记录
    devices := QueryMultiple(db)
    fmt.Println("query result:\n", devices)
}

你可能感兴趣的:(golang)