搜尋
首頁後端開發Golang無法使用 pgx 連線到 postgres 資料庫 AWS RDS

无法使用 pgx 连接到 postgres 数据库 AWS RDS

php小編子墨在使用pgx連接到Postgres資料庫AWS RDS時遇到了問題。他發現無法成功建立連接,儘管他已經按照官方文件和其他資源提供的指導進行了配置。他嘗試了多種方法,包括檢查資料庫權限、確認網路連線、修改設定檔等,但問題仍然存在。他希望能夠得到解決這個問題的有效方法。

問題內容

我嘗試使用github.com/jackc/pgx/v5 套件在Go 程式中連接到AWS RDS 中的postgres 資料庫,但出現以下錯誤:

failed to connect to `host=xxxxx.xxxxxxx.us-east-1.rds.amazonaws.com user=golangpg database=golangpg`: server error (FATAL: database "golangpg" does not exist (SQLSTATE 3D000))
exit status 1

即使明確指出資料庫不存在也是錯誤,但我已經建立了 RDS 資料庫,我也可以透過 pgAdmin 連接到該資料庫。但是當我嘗試在 Go 程式碼中進行連接時,出現了上述錯誤。

我檢查了以下幾點

  1. 安全群組允許所有流量通過 5432 連接埠
  2. RDS 中啟用公共存取
  3. 能夠透過 pgAdmin 連接到同一資料庫。
package database
    
    import (
        "context"
        "fmt"
        "os"
        "strconv"
    
        "github.com/jackc/pgx/v5"
        "github.com/joho/godotenv"
    )
    
    func PGConnection() *pgx.Conn {
        envErr := godotenv.Load()
        if envErr != nil {
            fmt.Println("Error in loading .env file, ", envErr)
        }
    
        host := os.Getenv("DB_URL")
        port := os.Getenv("DB_PORT")
        user := os.Getenv("DB_USERNAME")
        password := os.Getenv("DB_PASSWORD")
        dbname := os.Getenv("DB_NAME")
    
        portInt, er := strconv.Atoi(port)
        if er != nil {
            fmt.Println("Error in converting string to number", er)
        }
    
        var err error
    
        pgConnString := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=require", host, portInt, user, password, dbname)
    
        pgConn, err := pgx.Connect(context.Background(), pgConnString)
    
        if err != nil {
            fmt.Printf("Unable to connection to database: \n%v\n", err)
            os.Exit(1)
        } else {
            fmt.Println("Database connection establised to db ", dbname)
        }
    
        return pgConn
    }
    
    var Connection *pgx.Conn = PGConnection()

這裡可能有什麼錯誤。即使從 pgAdmin 我也可以建立表,但無法從我的 Go 程式碼連接。

解決方法

該問題是因為您的 RDS PostgreSQL 主機中不存在 資料庫「golangpg」。

RDS識別碼! =資料庫名稱

#我在這裡重新建立您的設定:

PostgreSQL RDS

執行相同的程式碼並得到相同的錯誤:

▶ go run main.go
Unable to connection to database: 
failed to connect to `host=golangdb.xxxx.eu-central-1.rds.amazonaws.com user=postgres database=golangdb`: server error (FATAL: database "golangdb" does not exist (SQLSTATE 3D000))
exit status 1

原因是資料庫「golangdb」不存在在我的PostgreSQL RDS中不存在。

連接到資料庫主機並列出可用的資料庫。

▶ psql --host=golangdb.xxxxx.eu-central-1.rds.amazonaws.com --username=postgres

postgres=> \l
                                                       List of databases
   Name    |  Owner   | Encoding | Locale Provider |   Collate   |    Ctype     
-----------+----------+----------+-----------------+-------------+-------------
 postgres  | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 
 rdsadmin  | rdsadmin | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8

這也是使用 dbname := "postgres" 有效的原因,因為資料庫存在於主機中。

▶ go run main.go
Database connection establised to db  postgres

建立新資料庫

#
postgres=> CREATE DATABASE golangdb;
CREATE DATABASE
postgres=> \l
                                                       List of databases
   Name    |  Owner   | Encoding | Locale Provider |   Collate   |    Ctype    
-----------+----------+----------+-----------------+-------------+-------------
 golangdb  | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 
 postgres  | postgres | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8 
 rdsadmin  | rdsadmin | UTF8     | libc            | en_US.UTF-8 | en_US.UTF-8

重試 go 程式碼

▶ go run main.go
Database connection establised to db  golangdb

以上是無法使用 pgx 連線到 postgres 資料庫 AWS RDS的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
使用GO編程語言構建可擴展系統使用GO編程語言構建可擴展系統Apr 25, 2025 am 12:19 AM

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

有效地使用Init功能的最佳實踐有效地使用Init功能的最佳實踐Apr 25, 2025 am 12:18 AM

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

INIT函數在GO軟件包中的執行順序INIT函數在GO軟件包中的執行順序Apr 25, 2025 am 12:14 AM

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

在GO中定義和使用自定義接口在GO中定義和使用自定義接口Apr 25, 2025 am 12:09 AM

CustomInterfacesingoarecrucialforwritingFlexible,可維護,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增強ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

在GO中使用接口進行模擬和測試在GO中使用接口進行模擬和測試Apr 25, 2025 am 12:07 AM

使用接口進行模擬和測試的原因是:接口允許定義合同而不指定實現方式,使得測試更加隔離和易於維護。 1)接口的隱式實現使創建模擬對像變得簡單,這些對像在測試中可以替代真實實現。 2)使用接口可以輕鬆地在單元測試中替換服務的真實實現,降低測試複雜性和時間。 3)接口提供的靈活性使得可以為不同測試用例更改模擬行為。 4)接口有助於從一開始就設計可測試的代碼,提高代碼的模塊化和可維護性。

在GO中使用init進行包裝初始化在GO中使用init進行包裝初始化Apr 24, 2025 pm 06:25 PM

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

GO的選擇語句:多路復用並發操作GO的選擇語句:多路復用並發操作Apr 24, 2025 pm 05:21 PM

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

GO中的高級並發技術:上下文和候補組GO中的高級並發技術:上下文和候補組Apr 24, 2025 pm 05:09 PM

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境