我正在尝试创建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!")
}
结果:成功连接!
但是当我尝试创建结构时,系统给我一个错误;
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()
}
结果:恐慌:拨打tcp:查找tcp /%!d(string = 5432):getaddrinfow: 找不到指定的类。
goroutine 1 [正在运行]:main.checkError(...)/main.go:11
main。(*数据库).IsOpened(...)/main.go:28 main.main()/main.go:34 + 0xcc
答案 0 :(得分:0)
发生这种情况是因为您具有具有数据类型的混搭。您已将端口号声明为字符串,但是在构建连接字符串时,已将端口号指定为整数,这会产生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
。您可以在string
int
更改为struct
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)