2013-03-08 247 views
0

我有贏的應用程序,當我希望將數據庫連接到我的應用程序 錯誤我得到這個錯誤:數據庫連接錯誤

An attempt to attach an auto-named database for file C:\Users\Aren\Desktop\DB\REGISTRATION.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

public class DALBase 
{ 
    protected SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\\Users\\Aren\\Desktop\\DB\\REGISTRATION.mdf;integrated Security=true ; User Instance=True"); 
    protected SqlCommand com = new SqlCommand(); 
    protected SqlDataAdapter da = new SqlDataAdapter(); 
    protected DataSet ds = new DataSet(); 

} 

public DataSet GetStudent(string filter) 
    { 

     DataSet dset = new DataSet(); 
     using (SqlCommand cmd = new SqlCommand()) 
     { 
      string cmdstring = string.Format("Select * from {0}" 
       , Common.Data.Student.Table_Name); 


      if (!string.IsNullOrEmpty(filter)) cmdstring += " where " + filter; 


      cmd.CommandText = cmdstring; 
      cmd.Connection = this.con; 
      cmd.Connection.Open(); 
      cmd.CommandText = cmdstring; 
      cmd.Connection = this.con; 
      SqlDataAdapter adapter = new SqlDataAdapter(cmd); 
      adapter.Fill(dset, Common.Data.Student.Table_Name); 
      return dset; 
     } 
    } 

注:我也有3項目在我的解決方案中,DALBASE和GETSTUDENT方法在一個項目中,我從其他項目調用它們爲我獲取數據。

+0

我不知道,但我對連接字符串中單斜槓和雙斜槓的使用感到困惑。它是否需要\\在Windows路徑中? – 2013-03-08 09:42:41

回答

0

我相信我以前遇到過這個問題。在我的情況下,我在Visual Studio中加載了一個應用程序,它在運行時會加載數據庫並連接到SQL Server。不知何故,當我關閉應用程序時,它並沒有從SQL SERVER中分離出數據庫,下一次我運行該應用程序時,它會抱怨類似的消息。

如果您將SSMS安裝爲打開到。\ SQLEXPRESS實例並查看是否附加了註冊* .mdf文件。或者如果你沒有SSMS打開你的命令行並輸入...

sqlcmd -S .\SQLEXPRESS -Q "select name from sys.databases" 

這將顯示你所有的數據庫連接/在線的實例。

希望這會有所幫助。