登录
首页 >  Golang >  Go问答

已连接到 postgres 服务器,但拒绝从数据库“student”的表“students”中获取数据

来源:stackoverflow

时间:2024-04-26 11:00:28 492浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《已连接到 postgres 服务器,但拒绝从数据库“student”的表“students”中获取数据》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
    _ "github.com/lib/pq"
)

func logfatal(err error) {
    if err != nil {
        log.fatal(err)
    }
}

const (
    host     = "localhost"
    port     = 5432
    user     = "blablabla"
    password = ""
    dbname   = "student"
)

type student struct {
    id          int    `json:"id"`
    name        string `json:"name"`
    department  string `json:"department"`
    year_joined string `json:"year_joined"`
}

var students []student

var db *sql.db

func main() {

    psqlinfo := fmt.sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, dbname)

    var err error

    db, err = sql.open("postgres", psqlinfo)
    logfatal(err)

    err = db.ping()
    if err != nil {
        log.fatal(err)
    }

    fmt.println("connected")

    router := mux.newrouter()
    router.handlefunc("/students", getstudents).methods("get")

    log.fatal(http.listenandserve(":8000", router))

}

func getstudents(w http.responsewriter, r *http.request) {
    var thestudent student

    students = []student{}

    rows, err := db.query("select * from students")

    if err != nil {
        fmt.print("there was an error", err)
    }

    for rows.next() {
        err := rows.scan(&thestudent.id, &thestudent.name, &thestudent.department, &thestudent.year_joined)

        if err != nil {
            log.fatal(err)
        }
        students = append(students, thestudent)

    }

    json.newencoder(w).encode(students)

}

这是数据库

last login: sat may 29 07:24:12 on ttys003
/applications/postgres.app/contents/versions/11/bin/psql -p5432 "student"
 ~   new-feature ●✚  /applications/postgres.app/contents/versions/11/bin/psql -p5432 "student"
psql (11.2)
type "help" for help.

student=# select * from students;
 id | name  | department | year_joined 
----+-------+------------+-------------
  1 | ola   | csc        | 1990
  2 | kenny | math       | 2019
(2 rows)

student=#

这是从 vscode 终端得到的结果

Connected
there was an error pq: relation "students" does not exist<nil>`enter code here`

正确答案


经过逐行调试,我意识到与数据库的连接有效,但问题出在 postgresql 语法上,该语法应该是“selectfrom from table”而不是“select * from table”。意味着它不支持 select 和 () 和 (*) from from 之间有空格。谢谢

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>