How to attach .mdf file to .SQLEXPRESS

2019-02-13 16:59发布

问题:

Tried this in as connection string

connectionString="Server=.\SQLEXPRESS;
    AttachDbFilename=E:\Database\dnn49.mdf;Database=dnn49; 
    Trusted_Connection=Yes;" 

but i get an error

Unable to open the physical file "E:\Database\dnn49.mdf". Operating system error 5: "5(Access is denied.)". Cannot attach the file 'E:\Database\dnn49.mdf' as database 'dnn49'.

What gives?

回答1:

You must check the SQL Server Service account has modify permissions over the physical file "dnn49.mdf" , and modify permissions also over the folder that contains the file.



回答2:

If you're attaching from SQL Server Management Studio, it also works to run SSMS as an administrator. This then can take advantage of the fact that the Administrators group has full control over the file. Another much more rare circumstance is that you'll get this Access Denied error because the database is already attached. This is probably more obvious unless you have multiple instances of SQL Server running and you already attached it to another instance possibly.



回答3:

i can't say whether you people got the solution for the problem or not, but i suggest a simple one here...

copy the mdf and ldf file to your SQLServer installation directory, you may place it in backup folder of the directory. then try it

i had used it many times...

Good Luck



回答4:

If you are still unable to attach the database after granting the NETWORK SERVICE (or other Service Account) Modify Permission to the folder, also add your own User ID (the one attaching) to the Folder with Modify Permission (even if member of Administrators and Administrators has Full Control on the Folder). Apparently, this is a bug in Windows 7.

You can remove your User ID from the folder after successfully attaching the database(s).



回答5:

One other suggestion is to turn off UAC (you can turn it off just temporary to verify if it is a permission problem).