005-Go 操作PostgreSQL数据库

package main

import(
    "fmt"
    "database/sql"
    _ "github.com/lib/pq"
    "github.com/kataras/iris"
    "github.com/kataras/iris/middleware/logger"
    "github.com/kataras/iris/middleware/recover"
)

const(
    host = "127.0.0.1"
    port = 5432
    user = "test"
    password = "test"
    dbname = "test"
)

type User struct{
    Uno        string `json:"uno"`
    Uname    string    `json:"uname"`
}

func main(){
    app := iris.New()
    
    app.Logger().SetLevel("debug")

    app.Use(recover.New())
    app.Use(logger.New())

    app.Get("/users", func(ctx iris.Context){
        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!")

        var users []User

        rows,err := db.Query("select uno,uname from t_user")
        if err != nil{
            panic(err.Error)
        }
        defer rows.Close()

        for rows.Next(){
            rows.Columns()

            var user User
            err = rows.Scan(&user.Uno,&user.Uname)

            if err != nil {
                panic(err.Error)
            }

            users = append(users, user)
        }

        ctx.JSON(users)
    })

    app.Get("/user", func(ctx iris.Context){
        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!")

        sqlQuery := `select uno,uname from t_user where uno=$1`

        var user User

        row := db.QueryRow(sqlQuery, ctx.URLParam("uno"))

        err = row.Scan(&user.Uno,&user.Uname)

        switch err{
        case sql.ErrNoRows:
            fmt.Println("No rows were returned!")
        case nil:
            fmt.Println(user)
            ctx.JSON(user)
        default:
            panic(err) 
        }

    })

    app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
}

 

你可能感兴趣的:(005-Go 操作PostgreSQL数据库)