Unable to connect to psql database

王林
Release: 2024-02-09 18:00:10
forward
1221 people have browsed it

无法连接到 psql 数据库

php editor Apple sometimes encounters the problem of "unable to connect to psql database" when performing database operations. This error message usually appears when using a PostgreSQL database and may be due to a connection failure due to some common reasons. There are many ways to solve this problem, including checking the database connection parameters, confirming whether the database is running, checking the network connection, etc. In this article, we will introduce some common solutions to help readers quickly solve this problem and perform database operations smoothly.

Question content

I am trying to connect to the database but I get an error when I make a curl request to the endpoint using the get method. I double checked the user credentials and granted full and super user rights. Here is the error I get when curling the endpoint:

santosh@pkg*$:curl -i localhost:8080/books/show
http/1.1 303 see other
content-type: text/html; charset=utf-8
location: /books
date: sat, 19 nov 2022 12:09:52 gmt
content-length: 33

<a href="/books">see other</a>.
Copy after login

Establish a connection with the database. When making a request to the database, these errors will be triggered:

santosh@pkg*$:go run main.go 
database connection successful.
2022/11/19 17:39:47 http: panic serving 127.0.0.1:44324: runtime error: invalid memory address or nil pointer dereference
goroutine 35 [running]:
net/http.(*conn).serve.func1()
        /usr/local/go/src/net/http/server.go:1850 +0xbf
panic({0x6960e0, 0x8e5630})
        /usr/local/go/src/runtime/panic.go:890 +0x262
database/sql.(*db).conn(0x0, {0x7593d0, 0xc00011a000}, 0x1)
        /usr/local/go/src/database/sql/sql.go:1288 +0x53
database/sql.(*db).query(0x6?, {0x7593d0, 0xc00011a000}, {0x6da967, 0x13}, {0x0, 0x0, 0x0}, 0x68?)
Copy after login

Main program:

var db *sql.DB

type Books struct {
    Isbn   string
    Title  string
    Author string
    Price  float32
}

func init() {
    var err error
    args := fmt.Sprintf("host=%s port=%d dbname=%s user='%s' password=%s sslmode=%s", "localhost", 5432, "bookstore", "santosh", "dts123", "disable")
    db, err := sql.Open("postgres", args)
    if err != nil {
        fmt.Printf("Creating Database %s", err)
    }
    if err = db.Ping(); err != nil {
        panic(err)
    }
    fmt.Println("Database connection succussful.")

}

func main() {
    http.HandleFunc("/", index)
    http.HandleFunc("/books", booksIndex)
    http.ListenAndServe(":8080", nil)
}

func index(w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, "/books", http.StatusSeeOther)
}

func booksIndex(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
        return
    }

    rows, err := db.Query("SELECT * FROM books")
    if err != nil {
        http.Error(w, http.StatusText(500), 500)
        return
    }
    defer rows.Close()

    bks := make([]Books, 0)
    for rows.Next() {
        bk := Books{}
        err := rows.Scan(&bk.Isbn, &bk.Title, &bk.Author, &bk.Price)
        if err != nil {
            http.Error(w, http.StatusText(500), 500)
            return
        }
        bks = append(bks, bk)
    }
    if err = rows.Err(); err != nil {
        http.Error(w, http.StatusText(500), 500)
        return
    }

}
Copy after login

I tried double checking the user permissions and database format and order. Everything conforms to the code. The connection is established but fails with a panic when querying the database.

Solution

You did not initialize the package-level db variables correctly.

The

:= operator is called a "short variable declaration" that declares and initializes a new variable in its block scope. Any variable with the same name in the outer scope will be "hidden".

To properly initialize package-level variables, you can use a simple assignment :

65 bedfd11e6f5

Alternatively you can use := but then use a different variable name and make sure it is used for the assignment:

var db *sql.DB

func init() {
    args := fmt.Sprintf("host=%s port=%d dbname=%s user='%s' password=%s sslmode=%s", "localhost", 5432, "bookstore", "santosh", "dts123", "disable")

    _db, err := sql.Open("postgres", args)
    if err != nil {
        fmt.Printf("Creating Database %s", err)
    }
    // ...

    db = _db // set "global"
}
Copy after login

The above is the detailed content of Unable to connect to psql database. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!