无法从Azure数据库中读取
本文关键字:读取 数据库 Azure | 更新日期: 2023-09-27 17:59:03
我正在尝试读取/写入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]", "");
}
}
}
}
请确保连接到数据库表单的IP在Azure中的数据库配置中为白名单。听起来像是防火墙问题。
我不知道是怎么回事,但将我的代码重新排列为以下内容解决了我的问题,我可以读取我想要的数据。
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());
}