【发布时间】:2021-06-23 23:12:51
【问题描述】:
我刚刚在“谷歌云平台”上设置了一个 SQL Server。我在那里创建了一个数据库和表。我使用 Microsoft 的“SQL Server Management Studio”(SSMS)来连接和创建数据库和表。这一切都奏效了。我根据谷歌的Cloud SQL指令设置了代理地址127.0.0.1:1443。这一切都奏效了。
但是,我想做的是使用 C# 应用程序连接到这个远程服务器。我使用 C# 程序连接到我机器上的 SQL Server 没有问题,但我不知道如何配置连接到 Google Cloud Platform 上的远程服务器。
对于我的代码,我使用的是 System.Data.SqlClient 库。
我的连接字符串如下。希望下面的代码足以告诉您发生了什么。当我调用loadInfoFromDatabase() 时,它会在遇到`connection.Open() 时失败。我在下面的代码中在它旁边写了“FAILS HERE”。
尝试不同的东西后,连接字符串有点猜测。任何帮助将不胜感激。
谢谢!
public string _connectionString = @"Server=127.0.0.1:1443;Database=MarsDatabase;User Id=sqlserver;Password=AAABBBCCC";
private void loadInfoFromDatabase()
{
string firstName, middleName, lastName, email, password, assignedTables;
string connectionString;
SqlDataReader dataReader;
connectionString = _connectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); //FAILS HERE...
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("loadInfoFromDatabse");
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText = "Select * From Info";
// Attempt to commit the transaction.
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
...
}
dataReader.Close();
command.Dispose();
// connection.Close();
transaction.Commit();
Console.WriteLine("Selection from managers table worked.");
}
catch (Exception ex)
{
}
}
}
【问题讨论】:
-
您声明
on the remote one on the Google Cloud Platform。您正在使用什么服务(Compute Engine、App Engine 等)?每个服务都有一个设置 Cloud SQL 连接的指南。 -
@John Hanley -- 我不确定。我是新手。我假设“SQL-Server”是服务。我在这件事上头晕目眩。我在设置时确实遇到了“Compute Engine”,但我没有选择它。我现在正在查看 Google Cloud Platform 控制台,但没有发现任何突出的地方。
-
你在哪个服务上运行你的代码?
-
@John Hanley -- 我不明白这个问题,这可能是我的问题的一部分。 :-) 有一个代理 Cloud SQL Auth 代理,它应该允许您通过本地 IP 127.0.0.1 进行连接。它适用于微软的 SSMS。我在本地 Windows 10 机器上的 Visual Studio 中使用 C#。
-
查看@Dondi 的回答。此外,您需要将您的 Windows 10 公共 IP 地址列入白名单,以便您可以连接到 Cloud SQL,除非您已配置 Cloud SQL 身份验证代理。 cloud.google.com/sql/docs/sqlserver/configure-ip 和 cloud.google.com/sql/docs/sqlserver/sql-proxy
标签: c# sql-server google-cloud-platform google-cloud-sql