连接到 Google Cloud SQL

use*_*128 5 google-app-engine google-cloud-sql google-cloud-platform

我已经设置了一个运行完美的 Google Cloud SQL,但是我在使用文档中给出的任何方法进行连接时遇到了问题:

磷酸二氢钾

$db = new PDO('mysql:unix_socket=/cloudsql/hello-php:my-cloudsql-instance;charset=utf8','<username>','<password>');
Run Code Online (Sandbox Code Playgroud)

mysql_连接

$conn = mysql_connect(':/cloudsql/hello-php:my-cloudsql-instance', '<username>', '<password>');
Run Code Online (Sandbox Code Playgroud)

mysqli

$sql = new mysqli(null, '<username>', '<password>', null, null, '/cloudsql/hello-php:my-cloudsql-instance');
Run Code Online (Sandbox Code Playgroud)

我可以从 MySQL Workbench 进行远程连接,但每当我尝试使用上述功能从网站上进行连接时,我都会收到“在‘读取初始通信数据包’时与 MySQL 服务器失去连接”的消息 - 但我通过授权网络授予了 Cloud SQL 访问权限并检查了 IP给予。我相信这与我不是尝试从 Google App Engine 而是从我自己的开发数据库进行连接这一事实有关。如何从 Google 外部进行连接!?

更新:我已经通过各种方式验证了我的 IP,但此代码仍然无法正常工作。

$host="173.xxx.xx.xxx" <-- given from Google Developers COnsole
$db_username="root";
$db_pasword="xxxx"; <-- password I set after creating the instance

mysql_connect("$host", "$db_username", "$db_password")or die("cannot connect");
Run Code Online (Sandbox Code Playgroud)

该页面给出错误:

警告:mysql_connect() [function.mysql-connect]:在“读取初始通信数据包”时失去与 MySQL 服务器的连接,系统错误:/..../connect.php 第 5 行中的 111 无法连接

当我尝试此 PDO 连接时,我也收到错误:

$dsn = 'mysql:host=173.xxx.xx.xxx;dbname=database_name';
$username = 'root';
$password = 'xxxx';

$dbh = new PDO($dsn, $username, $password);
Run Code Online (Sandbox Code Playgroud)

未捕获异常“PDOException”,消息为“SQLSTATE[HY000] [2003] 无法连接到“173.xxx.xx.xxx”(111)”上的 MySQL 服务器

Joa*_*son 4

您无法使用 unix 套接字(仅适用于本地计算机)进行远程连接,您需要通过网络进行连接。

Google简要描述了您需要做什么才能实现这一点,但基本上可以归结为您需要授权要连接的 IP 号码/范围,并使用实例的公共 IP 连接到数据库。