情况如下图所示:https://pasteboard.co/HSsFIgn.png
我有PostgreSQL可移植10.1和golang 1.10.2可移植。我写了一个简单的程序来从数据库中获取数据,但没有任何响应。代码是这样的:我没有编译错误,可以运行dbapp.exe,结果什么也没有,请参见上方粘贴的图片或下方的代码:谢谢任何提示。
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"log"
)
const (
DB_USER = "postgres"
DB_PASSWORD = ""
DB_NAME = "golang"
)
func main() {
dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable",
DB_USER, DB_PASSWORD, DB_NAME)
db, err := sql.Open("postgres", dbinfo)
checkErr(err)
defer db.Close()
var (
id int
name string
)
rows, err := db.Query("select id, song from music where id = 1")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
log.Println(id, name)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
}
func checkErr(err error) {
if err != nil {
fmt.Println(err)
panic(err)
}
}
答案 0 :(得分:0)
解决方案是sql.Open字符串,它已损坏或发生了什么,现在可以这样运行:
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"log"
)
func main() {
//necessary to change sql.Open strings
db, err := sql.Open("postgres", "user=postgres dbname=golang port=5432 sslmode=disable")
checkErr(err)
defer db.Close()
var (
id int
name string
)
rows, err := db.Query("select id, song from music where id = 1")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
log.Println(id, name)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
}
func checkErr(err error) {
if err != nil {
fmt.Println(err)
panic(err)
}
}