我有一个使用数据库 TopScores.mdf
的应用程序 JigSaw,它不包含在项目中。我想要做的是让应用程序在应用程序的文件夹中找到数据库。因此,例如,如果我将 .exe
文件和数据库文件从调试文件夹移动到桌面,应用程序应该使用桌面上的数据库,而不是在调试文件夹中搜索它。
如果我将它们放在调试文件夹中,则没有问题,并且与数据库的连接已建立,但是当我将它们放在桌面上时,我得到了这个:
Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. Database 'D:\Programing\Projects Visual Studio 2010\JigSaw\JigSaw\bin\Debug\TopScores.mdf' already exists. Choose a different database name. Cannot attach the file 'C:\Users\Addy\Desktop\Jigsaw\TopScores.mdf' as database TopScores.mdf
我的连接字符串是:
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
string connString = @"server =.\sqlexpress; Database=TopScores.mdf; trusted_connection=TRUE; AttachDbFileName= "+@appPath+@"\TopScores.mdf";
conn = new SqlConnection(connString);
抱歉我的英语不好:(
最佳答案
发生这种情况是因为您在连接到它时没有利用 User Instance=true;
。您从字面上告诉 SQL Server 将数据库从您第一次从中加载的目录附加到正在运行的 SQL 实例。
从正在运行的 SQL 实例中手动分离数据库,将连接字符串更改为使用 User Instance=true;
,从 Debug
文件夹中运行它,然后运行它来自 Desktop
,您会看到成功。
关于c# - 当我将解决方案移动到另一个目录时,为什么在使用 "Database already exists"时得到 "AttachDbFileName"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16090625/