2015-07-12 118 views
0

我使用以下命令從數據庫中檢索數據,但SqlConnection無法打開。它在scon.Open()處引發錯誤。我確定它是基本的,但我無法解決它。asp.net無法打開數據庫登錄失敗

protected void Page_Load(object sender, EventArgs e) { 
    SqlConnection scon = new SqlConnection("Data Source = .\\SQLEXPRESS; Database = populate.mdf; Integrated Security = true; Initial Catalog = populate"); 

    StringBuilder htmlString = new StringBuilder(); 

    if(!IsPostBack) 
    { 
     using (SqlCommand scmd = new SqlCommand()) 
     { 
      scmd.Connection = scon; 
      scmd.CommandType = CommandType.Text; 
      scmd.CommandText = "SELECT * FROM populate"; 

      scon.Open(); 

      SqlDataReader articleReader = scmd.ExecuteReader(); 

      htmlString.Append("'Populate page:'");     

      if (articleReader.HasRows) 
      { 
       while (articleReader.Read()) 
       { 
        htmlString.Append(articleReader["dateTime"]); 
        htmlString.Append(articleReader["firstName"]); 
        htmlString.Append(articleReader["lastName"]); 
        htmlString.Append(articleReader["address"]); 
        htmlString.Append(articleReader["details"]); 
       } 

       populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() }); 
       articleReader.Close(); 
       articleReader.Dispose(); 
      } 
     } 
    } 
} 

我使用此鏈接https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx作爲我的參考之一。如果這些信息有幫助,我還使用SQL Server 2008 R2 Express。

下面是錯誤消息的一部分:

SQLEXCEPTION(0x80131904):無法打開數據庫 「填充」 要求 由登錄。登錄失敗。

任何幫助將不勝感激。

+0

網站正在運行的用戶可能無法訪問數據庫。你使用的是IIS還是IIS Express? –

+0

@BrendanGreen:IIS Express。當我註釋掉上面的代碼時,我的GridView通過SqlDataSource顯示相同的數據。 – matt2605

+0

我仍然不確定:你的**數據庫**是否叫做'populate',並且你在該數據庫中處理的表是**也稱爲'populate'?看起來很奇怪.....如果你使用Management Studio連接到你的'。\ SQLEXPRESS'實例,你會發現什麼**數據庫**?在SQL Server中,**數據庫**包含**多個**表 - 所以這些通常不會被稱爲相同! –

回答

0

我解決了它。所有連接字符串和其他代碼都是正確的。數據庫只需要連接到Management Studio並加以特別關注。

0

https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#sse報價,如果你想使用.mdf文件作爲數據庫,你應該使用含有AttacheDbFileName下面的連接字符串。

<add name="ConnectionStringName" 
    providerName="System.Data.SqlClient" 
    connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" /> 
+0

謝謝,我試過了,我得到這個錯誤,直接指向數據庫:<<< SqlException(0x80131904):無法打開物理文件「[我的目錄] \ App_Data \ populate.mdf」。操作系統錯誤32:「32(未能檢索到此錯誤的文本,原因:15105)」>>> – matt2605

+0

另請參閱http://stackoverflow.com/questions/6347312/unable-to-open-the-physical-文件操作系統錯誤32試一試 – HarryQuake

+0

謝謝,很大的努力。我嘗試了很多不同的策略,但沒有奏效。我無法嘗試的一項是重置屬性|安全性|驗證用戶|編輯|允許|完全控制|確定。我似乎沒有正確的屬性功能。 – matt2605

相關問題