我正在尝试读取/写入Azure数据库,但在下面的代码中使用SqlDataReader时收到以下错误消息:
Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.
我可以连接到SQL Server Management Studio中的数据库。有关为什么会这样做以及如何解决这个问题的任何建议?
我的C#代码:
string connectionString = "Server=tcp:[xxxxx].database.windows.net,1433;Database=[xxxxx];User ID=[xxxxx]@[xxxxx];Password=[xxxxx];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = "SELECT [xxxxx], [xxxxx] FROM [xxxxx]";
using (SqlCommand cmd = new SqlCommand(sql))
{
using (SqlDataReader reader = Database.ExecuteReader(cmd))
{
if (!reader.Read())
{
throw new Exception("[xxxxx] not found.");
}
else
{
name = Database.GetStringValue(reader, "[xxxxx]", "");
}
}
}
}
答案 0 :(得分:0)
确保连接到数据库表单的IP在Azure中的数据库配置中列为白名单。听起来像firewall问题。
答案 1 :(得分:0)
我不知道如何将我的代码重新安排到下面的代码解决了我的问题,我可以阅读我想要的数据。
string connectionString = "Server=tcp: [xxxxx].database.windows.net,1433;Database=[xxxxx];User ID=[xxxxx]@[xxxxx];Password=[xxxxx];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
SqlConnection myConnection = new SqlConnection(connectionString);
try
{
myConnection.Open();
SqlDataReader reader = null;
SqlCommand myCommand = new SqlCommand("SELECT [xxxxx] FROM [xxxxx]", myConnection);
reader = myCommand.ExecuteReader();
if (!(reader.Read()))
throw new Exception("[xxxxx] not found.");
else
cert = reader["[xxxxx]"].ToString();
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}