{"id":1422,"library":"cloud-sql-python-connector","title":"Google Cloud SQL Python Connector","description":"The Google Cloud SQL Python Connector is a client library that helps connect Python applications to Google Cloud SQL databases. It automatically handles authentication, encryption, and secure connection management, acting as a smart proxy for your database connections. As of version 1.20.1, it provides robust and secure connectivity. The library is actively maintained by Google, with frequent updates aligning with Cloud SQL proxy and client library best practices.","status":"active","version":"1.20.1","language":"python","source_language":"en","source_url":"https://github.com/GoogleCloudPlatform/cloud-sql-python-connector","tags":["google-cloud","sql","database","connector","mysql","postgresql"],"install":[{"cmd":"pip install cloud-sql-python-connector[pymysql]","lang":"bash","label":"For MySQL using PyMySQL"},{"cmd":"pip install cloud-sql-python-connector[pg8000]","lang":"bash","label":"For PostgreSQL using pg8000"},{"cmd":"pip install cloud-sql-python-connector[psycopg2]","lang":"bash","label":"For PostgreSQL using psycopg2"}],"dependencies":[{"reason":"Required for connecting to MySQL databases via a connector extra.","package":"pymysql","optional":true},{"reason":"Required for connecting to PostgreSQL databases via a connector extra.","package":"pg8000","optional":true},{"reason":"Required for connecting to PostgreSQL databases via a connector extra (psycopg2-binary is commonly used for ease of installation).","package":"psycopg2-binary","optional":true}],"imports":[{"symbol":"Connector","correct":"from google.cloud.sql.connector import Connector"},{"symbol":"IPTypes","correct":"from google.cloud.sql.connector import IPTypes"}],"quickstart":{"code":"import os\nimport pymysql\nfrom google.cloud.sql.connector import Connector, IPTypes\n\n# Recommended: Use Application Default Credentials (ADC).\n# Ensure GOOGLE_APPLICATION_CREDENTIALS env var is set or ADC is configured.\n\n# Initialize Connector\nconnector = Connector()\n\n# Function to get a database connection\ndef get_db_connection():\n    try:\n        conn = connector.connect(\n            os.environ.get(\"INSTANCE_CONNECTION_NAME\", \"your-project:your-region:your-instance\"),\n            \"pymysql\", # Specify the DBAPI module you are using\n            user=os.environ.get(\"DB_USER\", \"root\"),\n            password=os.environ.get(\"DB_PASS\", \"\"),\n            db=os.environ.get(\"DB_NAME\", \"my_database\"),\n            ip_type=IPTypes.PUBLIC if os.environ.get(\"IP_TYPE\", \"public\").lower() == \"public\" else IPTypes.PRIVATE\n        )\n        return conn\n    except Exception as e:\n        print(f\"Error creating database connection: {e}\")\n        return None\n\n# Example Usage:\nif __name__ == \"__main__\":\n    # Set environment variables for testing, or rely on actual deployment configs.\n    # os.environ['INSTANCE_CONNECTION_NAME'] = 'your-project:your-region:your-instance'\n    # os.environ['DB_USER'] = 'my_user'\n    # os.environ['DB_PASS'] = 'my_password'\n    # os.environ['DB_NAME'] = 'my_database'\n    # os.environ['IP_TYPE'] = 'public' # or 'private'\n\n    conn = None\n    try:\n        conn = get_db_connection()\n        if conn:\n            with conn.cursor() as cursor:\n                cursor.execute(\"SELECT 1 + 1 AS solution;\")\n                result = cursor.fetchone()\n                print(f\"Database connection successful! Result: {result}\")\n    except Exception as e:\n        print(f\"An error occurred during database operation: {e}\")\n    finally:\n        if conn:\n            conn.close()\n        connector.close() # Important: close the connector when your application exits","lang":"python","description":"This quickstart demonstrates connecting to a MySQL Cloud SQL instance using PyMySQL. It relies on environment variables for sensitive information and the instance connection name. Ensure you have the `cloud-sql-python-connector[pymysql]` package installed. The connector automatically handles authentication using Application Default Credentials (ADC) or a service account key specified by `GOOGLE_APPLICATION_CREDENTIALS`."},"warnings":[{"fix":"Update your code to use `connector.connect(instance_connection_name, dbapi_module, ...)` and ensure you pass the DBAPI module (e.g., `pymysql`) as the second argument.","message":"Major breaking changes occurred in version 1.0.0. The primary connection method was renamed from `create_connection` to `connect`, and the `database_driver` argument was removed in favor of passing the DBAPI module object (e.g., `pymysql`) directly.","severity":"breaking","affected_versions":"<1.0.0"},{"fix":"Remove the `refresh_delay` parameter and its value from your `Connector` constructor calls. The library will manage token refreshes automatically.","message":"The `refresh_delay` parameter in the `Connector` constructor was removed, as its functionality is now handled internally and dynamically by the library.","severity":"breaking","affected_versions":">=1.15.0"},{"fix":"Install the connector with the correct extra: `pip install cloud-sql-python-connector[<driver>]`. For example, `pip install cloud-sql-python-connector[pymysql]`.","message":"You must install the appropriate database driver extra (e.g., `[pymysql]`, `[pg8000]`, `[psycopg2]`) when installing the connector, otherwise, connection attempts will fail with module not found errors.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always provide the full instance connection name in `PROJECT_ID:REGION:INSTANCE_NAME` format, typically retrieved from the Cloud SQL instance details in the Google Cloud Console.","message":"Incorrect `instance_connection_name` format. The correct format is `PROJECT_ID:REGION:INSTANCE_NAME`. Using just `INSTANCE_NAME` or other variations will lead to connection failures.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Set up Application Default Credentials by following the instructions at https://cloud.google.com/docs/authentication/external/set-up-adc. This often involves running `gcloud auth application-default login` or setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable.","message":"Application Default Credentials (ADC) were not found. The Cloud SQL Python Connector relies on ADC for authentication to Google Cloud. Ensure your environment is configured with valid credentials.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure your environment is authenticated with Google Cloud, typically by setting up Application Default Credentials (ADC). This can be done by running `gcloud auth application-default login` if using the Google Cloud SDK, or by setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path of a service account key file.","message":"The `cloud-sql-python-connector` library requires valid Google Cloud authentication credentials (e.g., via Application Default Credentials (ADC) or explicitly provided service account credentials). Without them, initialization or connection attempts will fail with a `DefaultCredentialsError`.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"search_vec":"'1.20.1':47 'act':35 'activ':57 'align':64 'applic':20 'authent':29 'automat':27 'best':72 'client':14,70 'cloud':2,8,23,66,76 'connect':18,33,43,53 'connector':5,11,79 'databas':25,42,78 'encrypt':30 'frequent':62 'googl':1,7,22,60,75 'google-cloud':74 'handl':28 'help':17 'librari':15,55,71 'maintain':58 'manag':34 'mysql':80 'postgresql':81 'practic':73 'provid':49 'proxi':39,68 'python':4,10,19 'robust':50 'secur':32,52 'smart':38 'sql':3,9,24,67,77 'updat':63 'version':46","created_at":"2026-04-09T03:47:15.259637+00:00","updated_at":"2026-04-16T02:37:15.805031+00:00","problems":[{"fix":"Ensure the `cloud-sql-python-connector` package is installed with its required database driver. For example, for MySQL: `pip install \"cloud-sql-python-connector[pymysql]\"`. For PostgreSQL: `pip install \"cloud-sql-python-connector[pg8000]\"` or `pip install \"cloud-sql-python-connector[asyncpg]\"`. Make sure this is included in your `requirements.txt` if deploying.","cause":"The `cloud-sql-python-connector` library or its parent `google` namespace package is not installed or not available in the Python environment. This often happens due to a missing entry in `requirements.txt` for deployments or an incorrect `pip install` command.","error":"ModuleNotFoundError: No module named 'google.cloud.sql.connector'"},{"fix":"Verify the database username and password are correct for the SQL user. If using IAM authentication, ensure the service account or user has the `Cloud SQL Client` IAM role on the Google Cloud Project and is added as an IAM database user on the Cloud SQL instance.","cause":"The database user, password, or IAM permissions are incorrect or insufficient for the connecting principal (user or service account) to access the Cloud SQL instance. This can also happen if the service account lacks the `cloudsql.client` role.","error":"sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1045, “Access denied for user 'your_user'@'cloudsqlproxy~'localIP' (using password: NO)”)"},{"fix":"Ensure the Cloud SQL Auth Proxy is running and correctly creating the Unix socket for your instance. Verify that the `instance_connection_name` (e.g., `project-id:region:instance-name`) in your application's connection string or environment variables (e.g., `CLOUD_SQL_INSTANCE_CONNECTION_NAME`) is exact. On platforms like App Engine Flex, ensure `cloud_sql_instances` is configured in `app.yaml`.","cause":"This error occurs when the application attempts to connect via a Unix domain socket, but the Cloud SQL Auth Proxy is not running, is misconfigured, or the instance connection name in the connection string is incorrect.","error":"sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket \"/cloudsql/<instance-connection-name>/.s.PGSQL.5432\"?"},{"fix":"Correct the package name to `cloud-sql-python-connector` in your `pip install` command or `requirements.txt`. For example, `pip install \"cloud-sql-python-connector[DRIVER]\"`. If using a slim Docker image (like Alpine), consider switching to a Debian-based image or explicitly installing build dependencies.","cause":"The package name used in `pip install` or `requirements.txt` is incorrect. The correct package name is `cloud-sql-python-connector`, not `google-cloud-sql-connector`. This can also occur if the base Docker image (e.g., Alpine Linux) lacks necessary system dependencies for the connector or its database drivers.","error":"ERROR: Could not find a version that satisfies the requirement google-cloud-sql-connector (from versions: none) ERROR: No matching distribution found for google-cloud-sql-connector."}],"ecosystem":"pypi","meta_description":null,"install_score":100,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"1.22.0","cli_name":"","cli_version":null,"type":"library","homepage":"https://cloud.google.com/sql/docs/postgres/connect-connectors","github":"https://github.com/GoogleCloudPlatform/cloud-sql-python-connector","docs":null,"changelog":"https://github.com/GoogleCloudPlatform/cloud-sql-python-connector/blob/main/CHANGELOG.md","pypi":"https://pypi.org/project/cloud-sql-python-connector/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["gcp","database","auth-security","http-networking"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-27","next_check":"2026-07-28","install_tag":"verified"}}