将PostgreSQL连接到Go语言。

huangapple go评论85阅读模式
英文:

connecting postgresql to go

问题

package main

import (
	"database/sql"
	"fmt"
	"html/template"
	"net/http"
	"unicode"

	_ "github.com/lib/pq"
	"golang.org/x/crypto/bcrypt"
)

/* const (
	host     = "localhost"
	port     = 5432
	user     = "postgres"
	password = "*******"
	dbname   = "db"
) */

var tpl *template.Template
var db *sql.DB

func main() {
	tpl, _ = template.ParseGlob("templates/*.html")
	var err error
	db, err = sql.Open("postgres", "root:password@tcp(localhost:localhost/db")
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()
	http.HandleFunc("/register", registerHandler)
	http.HandleFunc("/registerauth", registerAuthHandler)
	fmt.Println("Listening")
	http.ListenAndServe("localhost:8080", nil)
}

当我运行这段代码时,我遇到了一个错误:

panic: sql: unknown driver "postgresql" (forgotten import?)

顺便说一下,我只是在按照在线课程的指导进行操作,但他们使用的是MySQL,而我使用的是Postgres,我正在为我的论文做这个。

英文:
package main

import (
	"database/sql"
	"fmt"
	"html/template"
	"net/http"
	"unicode"

	_ "github.com/lib/pq"
	"golang.org/x/crypto/bcrypt"
)

/* const (
	host = "localhost"
	port = 5432
	user = "postgres"
	password = "*******"
	dbname = "db"
) */

var tpl *template.Template
var db *sql.DB

func main() {
	tpl, _ = template.ParseGlob("templates/*.html")
	var err error
	db, err = sql.Open("postgresql", "root:password@tcp(localhost:localhost/db")
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()
	http.HandleFunc("/register", registerHandler)
	http.HandleFunc("/registerauth", registerAuthHandler)
	fmt.Println("Listening")
	http.ListenAndServe("localhost:8080", nil)
}

When I run this I get an error:
> panic: sql: unknown driver "postgresql" (forgotten import?)

btw, I'm just following a lesson online but they are using MySQL while I on the other hand use Postgres and I'm doing this for my thesis

答案1

得分: 1

你应该使用 "postgres" 数据库驱动字符串,而不是 "postgresql"。

英文:

You should use the "postgres" database driver string, not "postgresql".

huangapple
  • 本文由 发表于 2022年1月2日 15:43:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/70554365.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定