0

I have created a Cloud SQL instance, and a new database. However, I can't seem to connect to the database using Cloud SQL Python Connector. I have followed the sample code and steps in the documentation, but still failed.

Error:

Traceback (most recent call last):
  File "c:\Users\my_name\my_path\gl_cloudsql_mysql_fx.py", line 149, in <module>
    print(bnm_data_db.isTableExist('MY_TABLE'))
  File "c:\Users\my_name\my_path\gl_cloudsql_mysql_fx.py", line 81, in isTableExist
    with self.__pool.connect() as db_conn:
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\engine\base.py", line 3245, in connect
    return self._connection_cls(self)
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\engine\base.py", line 145, in __init__
    self._dbapi_connection = engine.raw_connection()
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\engine\base.py", line 3269, in raw_connection
    return self.pool.connect()
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\pool\base.py", line 455, in connect
    return _ConnectionFairy._checkout(self)
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\pool\base.py", line 1270, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\pool\base.py", line 719, in checkout
    rec = pool._do_get()
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\pool\impl.py", line 168, in _do_get
    with util.safe_reraise():
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\util\langhelpers.py", line 147, in __exit__
    raise exc_value.with_traceback(exc_tb)
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\pool\impl.py", line 166, in _do_get
    return self._create_connection()
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\pool\base.py", line 396, in _create_connection
    return _ConnectionRecord(self)
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\pool\base.py", line 681, in __init__
    self.__connect()
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\pool\base.py", line 905, in __connect
    with util.safe_reraise():
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\util\langhelpers.py", line 147, in __exit__
    raise exc_value.with_traceback(exc_tb)
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\pool\base.py", line 901, in __connect
    self.dbapi_connection = connection = pool._invoke_creator(self)
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\sqlalchemy\pool\base.py", line 368, in <lambda>
    return lambda rec: creator_fn()
  File "c:\Users\my_name\my_path\gl_cloudsql_mysql_fx.py", line 27, in getconn
    conn: pymysql.connections.Connection = self.__connector.connect(
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\google\cloud\sql\connector\connector.py", line 154, in connect
    return connect_task.result()
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\concurrent\futures\_base.py", line 458, in result
    return self.__get_result()
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\concurrent\futures\_base.py", line 403, in __get_result
    raise self._exception
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\google\cloud\sql\connector\connector.py", line 261, in connect_async
    return await asyncio.wait_for(get_connection(), timeout)
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\asyncio\tasks.py", line 445, in wait_for
    return fut.result()
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\google\cloud\sql\connector\connector.py", line 257, in get_connection
    return await self._loop.run_in_executor(None, connect_partial)
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\concurrent\futures\thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\site-packages\google\cloud\sql\connector\pymysql.py", line 54, in connect
    socket.create_connection((ip_address, SERVER_PROXY_PORT)),
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\socket.py", line 845, in create_connection
    raise err
  File "C:\Users\my_name\Anaconda3\envs\composer-bis-gl-env\lib\socket.py", line 833, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

I run this python code on locally on my machine (in a Conda environment).

Here's my code:

from google.cloud.sql.connector import Connector
import sqlalchemy
import pymysql

connector = Connector()

# function to return the database connection
def getconn() -> pymysql.connections.Connection:
    conn: pymysql.connections.Connection = connector.connect(
      "my_project:my_location:my_instance",
      "pymysql",
      user="user",
      password="password",
      db="my_database",
    )
    return conn

# create connection pool
pool = sqlalchemy.create_engine(
  "mysql+pymysql://",
  creator=getconn,
)

# insert statement
check_table_statement = sqlalchemy.text(
  "SELECT count(*) from information_schema.tables",
)

with pool.connect() as db_conn:
  result = db_conn.execute(check_table_statement)
  print(result)

connector.close()

I have tried to include my IP address in the Cloud SQL instance. However, I am not sure which one is the correct address. I have check my IP address multiple ways, but all of them are different:

  1. Google
  2. whatsmyip.org
  3. cmd command nslookup myip.opendns.com resolver1.opendns.com

No luck with all of them.

Note:

  • I did not check the Allow only SSL connections box. So, I reckon, there is no need to include the CA certificate.
  • The CloudSQL instance is using Public IP.

Update: I have added full error.

1
  • were you able to get the Python Connector working? Feb 8 at 14:36

2 Answers 2

1

To solve this, check the following -

  1. Make sure you enabled Public IP on the Cloud SQL instance
  2. Then, create a user with hosts allowed as % (all IPs).
  3. Next, ensure that you have a database created by the name of my_database by clicking on the Databases button on the left navigation inside Cloud SQL dashboard.
  4. Ensure that you are including the right service credentials in your script with Cloud SQL Client role.

You should be able to connect. Do let me know if you face any issues, will update the answer accordingly :)

7
  • @Bismuth Habs were you able to resolve your issue using these steps? If not I can jump in and try to offer more assistance. Feb 8 at 14:36
  • @xprilion it seems that I am still unable to connect to Cloud SQL. As a temporary workaround, currently I use Cloud Editor to run my python code instead. And it is working. Feb 9 at 9:31
  • @JackWotherspoon no luck :( . Yes please jump in. Feb 9 at 9:32
  • @BismuthHabs what error message are you facing currently?
    – xprilion
    Feb 9 at 9:33
  • @BismuthHabs are you trying to connect to a Public IP or Private IP Cloud SQL instance? Feb 9 at 14:30
0

A couple things for you to try in order to resolve the ConnectionRefusedError.

  1. Make sure the Cloud SQL Admin API is enabled within your Google Cloud Project.
  2. Make sure the IAM principal you are using for authorization within your environment has the Cloud SQL Client Role granted to it.
  3. Double check that your instance connection name is correct (first argument being passed to the .connect method) by verifying it on the Cloud SQL instance overview page.
  4. If you are connecting to a Cloud SQL instance Private IP make sure you are connecting from a machine within the VPC network and that your code is updated for private IP connections:
from google.cloud.sql.connector import Connector, IPTypes
import sqlalchemy
import pymysql

connector = Connector()

# function to return the database connection
def getconn() -> pymysql.connections.Connection:
    conn: pymysql.connections.Connection = connector.connect(
      "my_project:my_location:my_instance",
      "pymysql",
      user="user",
      password="password",
      db="my_database",
      ip_type=IPTypes.PRIVATE,
    )
    return conn

Let me know if any of these help resolve your connection, otherwise I can take a deeper look into it for you :)

4
  • No. 1,2,3 ... check... No. 4. The instance is using Public IP. Still the same error. If there is anything else you need to know, let me know. Feb 10 at 8:11
  • I have added the full error in my question. Feb 10 at 8:21
  • @BismuthHabs how are you setting Application Default Credentials? What command/method are you using to set credentials? Feb 10 at 17:48
  • You will want to make sure that credentials are being set properly in your conda environment. Feb 10 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.