importosimportsqlalchemydefconnect_tcp_socket()-> sqlalchemy.engine.base.Engine:"""Initializes a TCP connection pool for a Cloud SQL instance of MySQL."""# Note: Saving credentials in environment variables is convenient, but not# secure - consider a more secure solution such as# Cloud Secret Manager (https://cloud.google.com/secret-manager) to help# keep secrets safe.db_host=os.environ["INSTANCE_HOST"]# e.g. '127.0.0.1' ('172.17.0.1' if deployed to GAE Flex)db_user=os.environ["DB_USER"]# e.g. 'my-db-user'db_pass=os.environ["DB_PASS"]# e.g. 'my-db-password'db_name=os.environ["DB_NAME"]# e.g. 'my-database'db_port=os.environ["DB_PORT"]# e.g. 3306pool=sqlalchemy.create_engine(# Equivalent URL:# mysql+pymysql://<db_user>:<db_pass>@<db_host>:<db_port>/<db_name>sqlalchemy.engine.url.URL.create(drivername="mysql+pymysql",username=db_user,password=db_pass,host=db_host,port=db_port,database=db_name,),# ...)returnpool
To see this snippet in the context of a web application, view the README on GitHub.
Note:
importcom.zaxxer.hikari.HikariConfig;importcom.zaxxer.hikari.HikariDataSource;importjavax.sql.DataSource;publicclassTcpConnectionPoolFactoryextendsConnectionPoolFactory{// Saving credentials in environment variables is convenient, but not secure - consider a more// secure solution such as https://cloud.google.com/secret-manager/ to help keep secrets safe.privatestaticfinalStringDB_USER=System.getenv("DB_USER");privatestaticfinalStringDB_PASS=System.getenv("DB_PASS");privatestaticfinalStringDB_NAME=System.getenv("DB_NAME");privatestaticfinalStringINSTANCE_HOST=System.getenv("INSTANCE_HOST");privatestaticfinalStringDB_PORT=System.getenv("DB_PORT");publicstaticDataSourcecreateConnectionPool(){// The configuration object specifies behaviors for the connection pool.HikariConfigconfig=newHikariConfig();// The following URL is equivalent to setting the config options below:// jdbc:mysql://<INSTANCE_HOST>:<DB_PORT>/<DB_NAME>?user=<DB_USER>&password=<DB_PASS>// See the link below for more info on building a JDBC URL for the Cloud SQL JDBC Socket Factory// https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory#creating-the-jdbc-url// Configure which instance and what database user to connect with.config.setJdbcUrl(String.format("jdbc:mysql://%s:%s/%s",INSTANCE_HOST,DB_PORT,DB_NAME));config.setUsername(DB_USER);// e.g. "root", "mysql"config.setPassword(DB_PASS);// e.g. "my-password"// ... Specify additional connection properties here.// ...// Initialize the connection pool using the configuration object.returnnewHikariDataSource(config);}}
To see this snippet in the context of a web application, view the README on GitHub.
constmysql=require('promise-mysql');constfs=require('fs');// createTcpPool initializes a TCP connection pool for a Cloud SQL// instance of MySQL.constcreateTcpPool=asyncconfig=>{// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.constdbConfig={host:process.env.INSTANCE_HOST,// e.g. '127.0.0.1'port:process.env.DB_PORT,// e.g. '3306'user:process.env.DB_USER,// e.g. 'my-db-user'password:process.env.DB_PASS,// e.g. 'my-db-password'database:process.env.DB_NAME,// e.g. 'my-database'// ... Specify additional properties here....config,};// Establish a connection to the database.returnmysql.createPool(dbConfig);};
To see this snippet in the context of a web application, view the README on GitHub.
packagecloudsqlimport("crypto/tls""crypto/x509""database/sql""errors""fmt""log""os""github.com/go-sql-driver/mysql")// connectTCPSocket initializes a TCP connection pool for a Cloud SQL// instance of MySQL.funcconnectTCPSocket()(*sql.DB,error){mustGetenv:=func(kstring)string{v:=os.Getenv(k)ifv==""{log.Fatalf("Fatal Error in connect_tcp.go: %s environment variable not set.",k)}returnv}// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.var(dbUser=mustGetenv("DB_USER")// e.g. 'my-db-user'dbPwd=mustGetenv("DB_PASS")// e.g. 'my-db-password'dbName=mustGetenv("DB_NAME")// e.g. 'my-database'dbPort=mustGetenv("DB_PORT")// e.g. '3306'dbTCPHost=mustGetenv("INSTANCE_HOST")// e.g. '127.0.0.1' ('172.17.0.1' if deployed to GAE Flex))dbURI:=fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true",dbUser,dbPwd,dbTCPHost,dbPort,dbName)// dbPool is the pool of database connections.dbPool,err:=sql.Open("mysql",dbURI)iferr!=nil{returnnil,fmt.Errorf("sql.Open: %w",err)}// ...returndbPool,nil}
To see this snippet in the context of a web application, view the README on GitHub.
usingMySql.Data.MySqlClient;usingSystem;namespaceCloudSql{publicclassMySqlTcp{publicstaticMySqlConnectionStringBuilderNewMysqlTCPConnectionString(){// Equivalent connection string:// "Uid=<DB_USER>;Pwd=<DB_PASS>;Host=<INSTANCE_HOST>;Database=<DB_NAME>;"varconnectionString=newMySqlConnectionStringBuilder(){// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.Server=Environment.GetEnvironmentVariable("INSTANCE_HOST"),// e.g. '127.0.0.1'// Set Host to 'cloudsql' when deploying to App Engine Flexible environmentUserID=Environment.GetEnvironmentVariable("DB_USER"),// e.g. 'my-db-user'Password=Environment.GetEnvironmentVariable("DB_PASS"),// e.g. 'my-db-password'Database=Environment.GetEnvironmentVariable("DB_NAME"),// e.g. 'my-database'// The Cloud SQL proxy provides encryption between the proxy and instance.SslMode=MySqlSslMode.Disabled,};connectionString.Pooling=true;// Specify additional properties here.returnconnectionString;}}}
To see this snippet in the context of a web application, view the README on GitHub.
tcp:&tcpadapter:mysql2# Configure additional properties here# Note: Saving credentials in environment variables is convenient, but not# secure - consider a more secure solution such as# Cloud Secret Manager (https://cloud.google.com/secret-manager) to help# keep secrets safe.username:<%= ENV["DB_USER"] %> # e.g. "my-database-user" password: <%=ENV["DB_PASS"]%># e.g. "my-database-password"database:<%= ENV.fetch("DB_NAME") { "vote_development" } %> host: "<%=ENV.fetch("INSTANCE_HOST"){"127.0.0.1"}%>" # '172.17.0.1' if deployed to GAE Flex port: <%= ENV.fetch("DB_PORT") { 3306 }%>
To see this snippet in the context of a web application, view the README on GitHub.
namespace Google\Cloud\Samples\CloudSQL\MySQL;use PDO;use PDOException;use RuntimeException;use TypeError;class DatabaseTcp{ public static function initTcpDatabaseConnection(): PDO { try { // Note: Saving credentials in environment variables is convenient, but not // secure - consider a more secure solution such as // Cloud Secret Manager (https://cloud.google.com/secret-manager) to help // keep secrets safe. $username = getenv('DB_USER'); // e.g. 'your_db_user' $password = getenv('DB_PASS'); // e.g. 'your_db_password' $dbName = getenv('DB_NAME'); // e.g. 'your_db_name' $instanceHost = getenv('INSTANCE_HOST'); // e.g. '127.0.0.1' ('172.17.0.1' for GAE Flex) // Connect using TCP $dsn = sprintf('mysql:dbname=%s;host=%s', $dbName, $instanceHost); // Connect to the database $conn = new PDO( $dsn, $username, $password, # ... ); } catch (TypeError $e) { throw new RuntimeException( sprintf( 'Invalid or missing configuration! Make sure you have set ' . '$username, $password, $dbName, and $instanceHost (for TCP mode). ' . 'The PHP error was %s', $e->getMessage() ), $e->getCode(), $e ); } catch (PDOException $e) { throw new RuntimeException( sprintf( 'Could not connect to the Cloud SQL Database. Check that ' . 'your username and password are correct, that the Cloud SQL ' . 'proxy is running, and that the database exists and is ready ' . 'for use. For more assistance, refer to %s. The PDO error was %s', 'https://cloud.google.com/sql/docs/mysql/connect-external-app', $e->getMessage() ), $e->getCode(), $e ); } return $conn; }}
Cloud SQL Auth Proxy invocation statement:
./cloud-sql-proxy --unix-socket /cloudsql INSTANCE_CONNECTION_NAME &
To see this snippet in the context of a web application, view the README on GitHub.
importosimportsqlalchemydefconnect_unix_socket()-> sqlalchemy.engine.base.Engine:"""Initializes a Unix socket connection pool for a Cloud SQL instance of MySQL."""# Note: Saving credentials in environment variables is convenient, but not# secure - consider a more secure solution such as# Cloud Secret Manager (https://cloud.google.com/secret-manager) to help# keep secrets safe.db_user=os.environ["DB_USER"]# e.g. 'my-database-user'db_pass=os.environ["DB_PASS"]# e.g. 'my-database-password'db_name=os.environ["DB_NAME"]# e.g. 'my-database'unix_socket_path=os.environ["INSTANCE_UNIX_SOCKET"]# e.g. '/cloudsql/project:region:instance'pool=sqlalchemy.create_engine(# Equivalent URL:# mysql+pymysql://<db_user>:<db_pass>@/<db_name>?unix_socket=<socket_path>/<cloud_sql_instance_name>sqlalchemy.engine.url.URL.create(drivername="mysql+pymysql",username=db_user,password=db_pass,database=db_name,query={"unix_socket":unix_socket_path},),# ...)returnpool
To see this snippet in the context of a web application, view the README on GitHub.
importcom.zaxxer.hikari.HikariConfig;importcom.zaxxer.hikari.HikariDataSource;importjavax.sql.DataSource;publicclassConnectorConnectionPoolFactoryextendsConnectionPoolFactory{// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.privatestaticfinalStringINSTANCE_CONNECTION_NAME=System.getenv("INSTANCE_CONNECTION_NAME");privatestaticfinalStringINSTANCE_UNIX_SOCKET=System.getenv("INSTANCE_UNIX_SOCKET");privatestaticfinalStringDB_USER=System.getenv("DB_USER");privatestaticfinalStringDB_PASS=System.getenv("DB_PASS");privatestaticfinalStringDB_NAME=System.getenv("DB_NAME");publicstaticDataSourcecreateConnectionPool(){// The configuration object specifies behaviors for the connection pool.HikariConfigconfig=newHikariConfig();// The following URL is equivalent to setting the config options below:// jdbc:mysql:///<DB_NAME>?cloudSqlInstance=<INSTANCE_CONNECTION_NAME>& // socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=<DB_USER>&password=<DB_PASS>// See the link below for more info on building a JDBC URL for the Cloud SQL JDBC Socket Factory// https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory#creating-the-jdbc-url// Configure which instance and what database user to connect with.config.setJdbcUrl(String.format("jdbc:mysql:///%s",DB_NAME));config.setUsername(DB_USER);// e.g. "root", "mysql"config.setPassword(DB_PASS);// e.g. "my-password"config.addDataSourceProperty("socketFactory","com.google.cloud.sql.mysql.SocketFactory");config.addDataSourceProperty("cloudSqlInstance",INSTANCE_CONNECTION_NAME);// Unix sockets are not natively supported in Java, so it is necessary to use the Cloud SQL// Java Connector to connect. When setting INSTANCE_UNIX_SOCKET, the connector will // call an external package that will enable Unix socket connections.// Note: For Java users, the Cloud SQL Java Connector can provide authenticated connections// which is usually preferable to using the Cloud SQL Proxy with Unix sockets.// See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.if(INSTANCE_UNIX_SOCKET!=null){config.addDataSourceProperty("unixSocketPath",INSTANCE_UNIX_SOCKET);}// cloudSqlRefreshStrategy set to "lazy" is used to perform a// refresh when needed, rather than on a scheduled interval.// This is recommended for serverless environments to// avoid background refreshes from throttling CPU.config.addDataSourceProperty("cloudSqlRefreshStrategy","lazy");// ... Specify additional connection properties here.// ...// Initialize the connection pool using the configuration object.returnnewHikariDataSource(config);}}
To see this snippet in the context of a web application, view the README on GitHub.
constmysql=require('promise-mysql');// createUnixSocketPool initializes a Unix socket connection pool for// a Cloud SQL instance of MySQL.constcreateUnixSocketPool=asyncconfig=>{// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.returnmysql.createPool({user:process.env.DB_USER,// e.g. 'my-db-user'password:process.env.DB_PASS,// e.g. 'my-db-password'database:process.env.DB_NAME,// e.g. 'my-database'socketPath:process.env.INSTANCE_UNIX_SOCKET,// e.g. '/cloudsql/project:region:instance'// Specify additional properties here....config,});};
To see this snippet in the context of a web application, view the README on GitHub.
usingMySql.Data.MySqlClient;usingSystem;namespaceCloudSql{publicclassMySqlUnix{publicstaticMySqlConnectionStringBuilderNewMysqlUnixSocketConnectionString(){// Equivalent connection string:// "Server=<INSTANCE_UNIX_SOCKET>;Uid=<DB_USER>;Pwd=<DB_PASS>;Database=<DB_NAME>;Protocol=unix"varconnectionString=newMySqlConnectionStringBuilder(){// The Cloud SQL proxy provides encryption between the proxy and instance.SslMode=MySqlSslMode.Disabled,// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.Server=Environment.GetEnvironmentVariable("INSTANCE_UNIX_SOCKET"),// e.g. '/cloudsql/project:region:instance'UserID=Environment.GetEnvironmentVariable("DB_USER"),// e.g. 'my-db-userPassword=Environment.GetEnvironmentVariable("DB_PASS"),// e.g. 'my-db-password'Database=Environment.GetEnvironmentVariable("DB_NAME"),// e.g. 'my-database'ConnectionProtocol=MySqlConnectionProtocol.UnixSocket};connectionString.Pooling=true;// Specify additional properties here.returnconnectionString;}}}
To see this snippet in the context of a web application, view the README on GitHub.
packagecloudsqlimport("database/sql""fmt""log""os"_"github.com/go-sql-driver/mysql")// connectUnixSocket initializes a Unix socket connection pool for// a Cloud SQL instance of MySQL.funcconnectUnixSocket()(*sql.DB,error){mustGetenv:=func(kstring)string{v:=os.Getenv(k)ifv==""{log.Fatalf("Fatal Error in connect_unix.go: %s environment variable not set.",k)}returnv}// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.var(dbUser=mustGetenv("DB_USER")// e.g. 'my-db-user'dbPwd=mustGetenv("DB_PASS")// e.g. 'my-db-password'dbName=mustGetenv("DB_NAME")// e.g. 'my-database'unixSocketPath=mustGetenv("INSTANCE_UNIX_SOCKET")// e.g. '/cloudsql/project:region:instance')dbURI:=fmt.Sprintf("%s:%s@unix(%s)/%s?parseTime=true",dbUser,dbPwd,unixSocketPath,dbName)// dbPool is the pool of database connections.dbPool,err:=sql.Open("mysql",dbURI)iferr!=nil{returnnil,fmt.Errorf("sql.Open: %w",err)}// ...returndbPool,nil}
To see this snippet in the context of a web application, view the README on GitHub.
unix:&unixadapter:mysql2# Configure additional properties here.# Note: Saving credentials in environment variables is convenient, but not# secure - consider a more secure solution such as# Cloud Secret Manager (https://cloud.google.com/secret-manager) to help# keep secrets safe.username:<%= ENV["DB_USER"] %> # e.g. "my-database-user" password: <%=ENV["DB_PASS"]%># e.g. "my-database-password"database:<%= ENV.fetch("DB_NAME") { "vote_development" } %> # Specify the Unix socket path as host socket: "<%=ENV["INSTANCE_UNIX_SOCKET"]%>"
To see this snippet in the context of a web application, view the README on GitHub.
namespace Google\Cloud\Samples\CloudSQL\MySQL;use PDO;use PDOException;use RuntimeException;use TypeError;class DatabaseUnix{ public static function initUnixDatabaseConnection(): PDO { try { // Note: Saving credentials in environment variables is convenient, but not // secure - consider a more secure solution such as // Cloud Secret Manager (https://cloud.google.com/secret-manager) to help // keep secrets safe. $username = getenv('DB_USER'); // e.g. 'your_db_user' $password = getenv('DB_PASS'); // e.g. 'your_db_password' $dbName = getenv('DB_NAME'); // e.g. 'your_db_name' $instanceUnixSocket = getenv('INSTANCE_UNIX_SOCKET'); // e.g. '/cloudsql/project:region:instance' // Connect using UNIX sockets $dsn = sprintf( 'mysql:dbname=%s;unix_socket=%s', $dbName, $instanceUnixSocket ); // Connect to the database. $conn = new PDO( $dsn, $username, $password, # ... ); } catch (TypeError $e) { throw new RuntimeException( sprintf( 'Invalid or missing configuration! Make sure you have set ' . '$username, $password, $dbName, ' . 'and $instanceUnixSocket (for UNIX socket mode). ' . 'The PHP error was %s', $e->getMessage() ), (int) $e->getCode(), $e ); } catch (PDOException $e) { throw new RuntimeException( sprintf( 'Could not connect to the Cloud SQL Database. Check that ' . 'your username and password are correct, that the Cloud SQL ' . 'proxy is running, and that the database exists and is ready ' . 'for use. For more assistance, refer to %s. The PDO error was %s', 'https://cloud.google.com/sql/docs/mysql/connect-external-app', $e->getMessage() ), (int) $e->getCode(), $e ); } return $conn; }}
If you're having problems connecting, check the following pages for help debugging or finding solutions to known issues:
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-04-17 UTC.