2015-06-22 123 views
0

我想讀/寫一個Azure數據庫,但我在下面我的代碼使用SqlDataReader中時收到以下錯誤信息:無法從Azure數據庫讀取

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

請確保您連接到數據庫形式的IP是在Azure中的數據庫配置白名單。聽起來像我firewall問題。

+0

我聽說我的IP已經被白名單列出,我可以連接到SQL Server Management Studio中的數據庫。 – Bhav

+0

但是Management Studio是否在運行生產代碼的同一臺服務器上?或者你是從桌面還是不同的開發環境連接?如果您確定環境相同,那麼它可能不是防火牆問題。 –

+0

是的,Management Studio與我的代碼位於同一臺服務器上。 – Bhav

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()); 
     }