将PostgreSQL连接到Go语言。

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

connecting postgresql to go

问题

  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "html/template"
  6. "net/http"
  7. "unicode"
  8. _ "github.com/lib/pq"
  9. "golang.org/x/crypto/bcrypt"
  10. )
  11. /* const (
  12. host = "localhost"
  13. port = 5432
  14. user = "postgres"
  15. password = "*******"
  16. dbname = "db"
  17. ) */
  18. var tpl *template.Template
  19. var db *sql.DB
  20. func main() {
  21. tpl, _ = template.ParseGlob("templates/*.html")
  22. var err error
  23. db, err = sql.Open("postgres", "root:password@tcp(localhost:localhost/db")
  24. if err != nil {
  25. panic(err.Error())
  26. }
  27. defer db.Close()
  28. http.HandleFunc("/register", registerHandler)
  29. http.HandleFunc("/registerauth", registerAuthHandler)
  30. fmt.Println("Listening")
  31. http.ListenAndServe("localhost:8080", nil)
  32. }

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

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

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

英文:
  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "html/template"
  6. "net/http"
  7. "unicode"
  8. _ "github.com/lib/pq"
  9. "golang.org/x/crypto/bcrypt"
  10. )
  11. /* const (
  12. host = "localhost"
  13. port = 5432
  14. user = "postgres"
  15. password = "*******"
  16. dbname = "db"
  17. ) */
  18. var tpl *template.Template
  19. var db *sql.DB
  20. func main() {
  21. tpl, _ = template.ParseGlob("templates/*.html")
  22. var err error
  23. db, err = sql.Open("postgresql", "root:password@tcp(localhost:localhost/db")
  24. if err != nil {
  25. panic(err.Error())
  26. }
  27. defer db.Close()
  28. http.HandleFunc("/register", registerHandler)
  29. http.HandleFunc("/registerauth", registerAuthHandler)
  30. fmt.Println("Listening")
  31. http.ListenAndServe("localhost:8080", nil)
  32. }

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:

确定