gpt4 book ai didi

database - 如何解决 go 编程语言中的数据库结构问题?

转载 作者:数据小太阳 更新时间:2023-10-29 03:19:58 25 4
gpt4 key购买 nike

我正在尝试创建 postgresql 数据库结构以在 Golang 中自动化系统。

此代码有效;

package main

import (
"database/sql"
"fmt"

_ "github.com/lib/pq"
)

func checkError(err error){
if err!=nil{
panic(err)
}
}

const (
host = "localhost"
port = 5432
user = "postgres"
password = "123"
dbname = "DatabaseName"
)

func main() {
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)
checkError(err)

err = db.Ping()
checkError(err)

defer db.Close()
fmt.Println("Successfully connected!")
}

Result: Successfully connected!

但是当我试图创建一个结构时,系统给我一个错误;

package main

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

func checkError(err error){
if err!=nil{
panic(err)
}
}

type Database struct{
host, port, user, password, dbname string
db *sql.DB
}

func(d *Database) Open(){
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+"password=%s dbname=%s sslmode=disable", d.host, d.port, d.user, d.password, d.dbname)
db, err := sql.Open("postgres", psqlInfo)
checkError(err)
d.db = db
}

func(d *Database) IsOpened() {
checkError(d.db.Ping())
}

func main() {
a := Database{host: "localhost", port: "5432", user: "postgres", password: "123", dbname: "DatabaseName"}
a.Open()
a.IsOpened()
}

Result: panic: dial tcp: lookup tcp/%!d(string=5432): getaddrinfow: The specified class could not be found.

goroutine 1 [running]: main.checkError(...) /main.go:11

main.(*Database).IsOpened(...) /main.go:28 main.main() /main.go:34 +0xcc

最佳答案

发生这种情况是因为您有数据类型的混搭。您已将端口号声明为字符串,但是在构建连接字符串时,您已将端口号指定为整数,这将生成 host=localhost port=%!d(string=5432) user=postgres password=123 dbname=DatabaseName sslmode=disable 错误的连接字符串。您的连接字符串应该是 host=localhost port=5432 user=postgres password=123 dbname=DatabaseName sslmode=disable。您可以在 struct

中将端口号数据类型从 string 更改为 int
type Database struct {
host, user, password, dbname string
port int
db *sql.DB
}

https://play.golang.org/p/yP3Y-0NdloQ

或者您可以在构建连接字符串时将端口号类型从%d更改为%s

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

https://play.golang.org/p/e61dOUg0MA-

关于database - 如何解决 go 编程语言中的数据库结构问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55549720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com