Conectar o pgx a um banco de dados do dialeto PostgreSQL
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Nesta página, explicamos como conectar o driver pgx do PostgreSQL a um banco de dados de dialeto do PostgreSQL
no Spanner. pgx é um driver do Go para PostgreSQL.
Verifique se o PGAdapter está em execução na mesma máquina que o
aplicativo que está se conectando usando o driver pgx do PostgreSQL.
O pgx exige um nome de usuário e uma senha na string de conexão.
O PGAdapter ignora esses comandos.
Por padrão, o PGAdapter desativa o SSL. Por padrão, o pgx primeiro
tenta se conectar com o SSL ativado. Desativar o SSL na solicitação de conexão acelera o processo, já que exige uma viagem de ida e volta a menos.
connString:="postgres://uid:pwd@APPLICATION_HOST:PORT/DATABASE_NAME?sslmode=disable"ctx:=context.Background()conn,err:=pgx.Connect(ctx,connString)iferr!=nil{returnerr}deferconn.Close(ctx)vargreetingstringerr=conn.QueryRow(ctx,"select 'Hello world!' as hello").Scan(&greeting)iferr!=nil{returnerr}fmt.Printf("Greeting from Cloud Spanner PostgreSQL: %v\n",greeting)
Substitua:
APPLICATION_HOST: o nome do host ou endereço IP da máquina em que o PGAdapter está sendo executado. Se você estiver executando localmente, use localhost.
PORT: o número da porta em que o PGAdapter está
em execução. Mude isso na string de conexão se o PGAdapter estiver
sendo executado em uma porta personalizada. Caso contrário, use a porta padrão, 5432.
Soquetes de domínio Unix
Nesta seção, explicamos como usar soquetes de domínio Unix para conectar o driver pgx do PostgreSQL a um banco de dados de dialeto PostgreSQL. Use soquetes de domínio Unix para ter a menor latência possível.
Para usar soquetes de domínio Unix, o PGAdapter precisa estar em execução no mesmo host que o aplicativo cliente.
connString:="host=/tmp port=PORT database=DATABASE_NAME"ctx:=context.Background()conn,err:=pgx.Connect(ctx,connString)iferr!=nil{returnerr}deferconn.Close(ctx)vargreetingstringerr=conn.QueryRow(ctx,"select 'Hello world!' as hello").Scan(&greeting)iferr!=nil{returnerr}fmt.Printf("Greeting from Cloud Spanner PostgreSQL: %v\n",greeting)
Substitua:
/tmp: o diretório de soquete de domínio padrão para
PGAdapter. Isso pode ser mudado usando o argumento de linha de comando -dir.
PORT: o número da porta em que o PGAdapter está
em execução. Mude isso na string de conexão se o PGAdapter estiver
sendo executado em uma porta personalizada. Caso contrário, use a porta padrão, 5432.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-05 UTC."],[],[],null,["# Connect pgx to a PostgreSQL-dialect database\n\nThis page explains how to connect the PostgreSQL pgx driver to a PostgreSQL-dialect database\nin Spanner. `pgx` is a Golang driver for PostgreSQL.\n\nVerify that PGAdapter is running on the same machine as the\napplication that is connecting using the PostgreSQL pgx driver.\n\nFor more information, see [Start PGAdapter](/spanner/docs/pgadapter-start).\n\n- `pgx` requires a username and password in the connection string. PGAdapter ignores these.\n- By default, PGAdapter disables SSL. `pgx` by default first tries to connect with SSL enabled. Disabling SSL in the connection request speeds up the connection process, as it requires one fewer round trip.\n\n connString := \"postgres://uid:pwd@\u003cvar translate=\"no\"\u003eAPPLICATION_HOST\u003c/var\u003e:\u003cvar translate=\"no\"\u003ePORT\u003c/var\u003e/\u003cvar translate=\"no\"\u003eDATABASE_NAME\u003c/var\u003e?sslmode=disable\"\n ctx := context.Background()\n conn, err := pgx.Connect(ctx, connString)\n if err != nil {\n return err\n }\n defer conn.Close(ctx)\n\n var greeting string\n err = conn.QueryRow(ctx, \"select 'Hello world!' as hello\").Scan(&greeting)\n if err != nil {\n return err\n }\n fmt.Printf(\"Greeting from Cloud Spanner PostgreSQL: %v\\n\", greeting)\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003eAPPLICATION_HOST\u003c/var\u003e: the hostname or IP address of the machine where PGAdapter is running. If running locally, you can use `localhost`.\n- \u003cvar translate=\"no\"\u003ePORT\u003c/var\u003e: the port number where PGAdapter is running. Change this in the connection string if PGAdapter is running on a custom port. Otherwise, use the default port, `5432`.\n\n### Unix domain sockets\n\nThis section explains how to use Unix domain sockets to connect the\nPostgreSQL pgx driver to a PostgreSQL-dialect database. Use Unix domain sockets for the lowest\npossible latency.\n\nTo use Unix domain sockets, PGAdapter must be running on the\nsame host as the client application. \n\n connString := \"host=\u003cvar translate=\"no\"\u003e/tmp\u003c/var\u003e port=\u003cvar translate=\"no\"\u003ePORT\u003c/var\u003e database=\u003cvar translate=\"no\"\u003eDATABASE_NAME\u003c/var\u003e\"\n ctx := context.Background()\n conn, err := pgx.Connect(ctx, connString)\n if err != nil {\n return err\n }\n defer conn.Close(ctx)\n\n var greeting string\n err = conn.QueryRow(ctx, \"select 'Hello world!' as hello\").Scan(&greeting)\n if err != nil {\n return err\n }\n fmt.Printf(\"Greeting from Cloud Spanner PostgreSQL: %v\\n\", greeting)\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003e/tmp\u003c/var\u003e: the default domain socket directory for PGAdapter. This can be changed using the `-dir` command line argument.\n- \u003cvar translate=\"no\"\u003ePORT\u003c/var\u003e: the port number where PGAdapter is running. Change this in the connection string if PGAdapter is running on a custom port. Otherwise, use the default port, `5432`.\n\nWhat's next\n-----------\n\n- Learn more about [PGAdapter](/spanner/docs/pgadapter).\n- Learn more about [pgx Connection Options](https://github.com/GoogleCloudPlatform/pgadapter/blob/postgresql-dialect/docs/pgx.md) in the PGAdapter GitHub repository."]]