Cannot open database “MyDb” requested by the login

2019-08-20 02:05发布

问题:

I have been connecting to my local database (SQL Express) fine all day from my C# console application.

I have made an update, where I create a database and table from within the C# code using ADO.NET

When I do this, my normal connection string fails, which is

    Data Source=.\\sqlexpress;  Trusted_Connection=True;  Initial Catalog=ThisIsMyDataBase;

The error message is

Cannot open database "ThisIsMyDataBase" requested by the login. The login failed.\r\nLogin failed for user 'My-PC\\MrD'.

If I open the tables in SSMS, then I can access everything, using Windows Authentication.

I was under the impression that the Trusted_Connection=True would mean I have permission, and that I'm accessing it with my Windows account (not an SQL account) would mean I don't see this issue, but I'm clearly wrong. I'm not sure how to solve this.

回答1:

The error itself is saying the user dont have access failed for user 'My-PC\\MrD'. do a login for the user from sql server itself



回答2:

You propably do not have the sql server login, which is associated with your WIN user, mapped to a database user.

Check that your model database (under System databases in management studio) has your WIN user listed under Security/Users. If not, add it. Then delete the MyDb database and create it again using you code. The CREATE DATABASE statement uses a copy of the model database to create the new database and its metadata.



回答3:

I have the solution but I don't understand it at all

The answer is to rename the database with less characters. My actual database was 27 characters long, I've just given it a 4 character long name (simply called My01) and it works fine.