Conectar psycopg3 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 psycopg3 do PostgreSQL a um banco de dados com dialeto PostgreSQL no Spanner. psycopg3 é um driver Python para PostgreSQL.
Verifique se o PGAdapter está em execução na mesma máquina que o
aplicativo que está se conectando usando o driver psycopg3 do PostgreSQL.
importpsycopgwithpsycopg.connect("host=APPLICATION_HOST port=PORT dbname=DATABASE_NAME sslmode=disable")asconn:conn.autocommit=Truewithconn.cursor()ascur:cur.execute("select 'Hello world!' as hello")print("Greeting from Cloud Spanner PostgreSQL:",cur.fetchone()[0])
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 se conectar 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.
Verifique se o driver JDBC do PostgreSQL foi carregado.
importpsycopgwithpsycopg.connect("host=/tmpport=PORTdbname=DATABASE_NAME") as conn:conn.autocommit=Truewithconn.cursor()ascur:cur.execute("select 'Hello world!' as hello")print("Greetings from Cloud Spanner PostgreSQL:",cur.fetchone()[0])
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.
Para mais informações sobre as opções de conexão do driver psycopg3 do PostgreSQL,
consulte Opções de conexão do
psycopg3
no repositório do PGAdapter no GitHub.
[[["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 psycopg3 to a PostgreSQL-dialect database\n\nThis page explains how to connect the [PostgreSQL psycopg3 driver](https://www.psycopg.org/psycopg3/) to\na PostgreSQL-dialect database in Spanner. `psycopg3` is a Python\ndriver for PostgreSQL.\n\n1. Verify that PGAdapter is running on the same machine as the\n application that is connecting using the PostgreSQL psycopg3 driver.\n\n export GOOGLE_APPLICATION_CREDENTIALS=/\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003eCREDENTIALS_FILE_PATH\u003c/span\u003e\u003c/var\u003e/credentials.json\n docker pull gcr.io/cloud-spanner-pg-adapter/pgadapter\n docker run \\\n -d -p 5432:5432 \\\n -v ${GOOGLE_APPLICATION_CREDENTIALS}:${GOOGLE_APPLICATION_CREDENTIALS}:ro \\\n -e GOOGLE_APPLICATION_CREDENTIALS \\\n gcr.io/cloud-spanner-pg-adapter/pgadapter \\\n -p \u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003ePROJECT_NAME\u003c/span\u003e\u003c/var\u003e -i \u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003eINSTANCE_NAME\u003c/span\u003e\u003c/var\u003e \\\n -x\n\n For more information, see [Start PGAdapter](/spanner/docs/pgadapter-start).\n2. Connect to PGAdapter using TCP.\n\n import psycopg\n\n with psycopg.connect(\"host=\u003cvar translate=\"no\"\u003eAPPLICATION_HOST\u003c/var\u003e port=\u003cvar translate=\"no\"\u003ePORT\u003c/var\u003e dbname=\u003cvar translate=\"no\"\u003eDATABASE_NAME\u003c/var\u003e sslmode=disable\") as conn:\n conn.autocommit = True\n with conn.cursor() as cur:\n cur.execute(\"select 'Hello world!' as hello\")\n print(\"Greeting from Cloud Spanner PostgreSQL:\", cur.fetchone()[0])\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eAPPLICATION_HOST\u003c/var\u003e: the hostname or IP address of the machine where PGAdapter is running. If running locally, 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 to a\nPostgreSQL-dialect database. Use Unix domain sockets for the lowest possible latency.\n\nTo use Unix domain sockets, PGAdapter must be running on the\nsame host as the client application.\n\nVerify the PostgreSQL JDBC driver is loaded. \n\n import psycopg\n\n with psycopg.connect(\"host=\u003cvar translate=\"no\"\u003e/tmp\u003c/var\u003e\n port=\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003ePORT\u003c/span\u003e\u003c/var\u003e\n dbname=\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003eDATABASE_NAME\u003c/span\u003e\u003c/var\u003e\") as conn:\n conn.autocommit = True\n with conn.cursor() as cur:\n cur.execute(\"select 'Hello world!' as hello\")\n print(\"Greetings from Cloud Spanner PostgreSQL:\", cur.fetchone()[0])\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- For more information about PostgreSQL psycopg3 driver connection options, see [psycopg3 Connection\n Options](https://github.com/GoogleCloudPlatform/pgadapter/blob/-/docs/psycopg3.md) in the PGAdapter GitHub repository."]]