2013-03-08 401 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" 

这将显示你所有的数据库连接/在线的实例。

希望这会有所帮助。