Ошибка cannot open database requested

I have created a web service which is saving some data into to db. But I am getting this error:

Cannot open database «test» requested by the login. The login failed. Login failed for user ‘xyzASPNET’.

My connection string is

Data Source=.SQLExpress;Initial Catalog=IFItest;Integrated Security=True

marc_s's user avatar

marc_s

729k174 gold badges1327 silver badges1455 bronze badges

asked Apr 4, 2010 at 21:11

coure2011's user avatar

coure2011coure2011

39.9k83 gold badges214 silver badges342 bronze badges

2

Well, the error is pretty clear, no? You are trying to connect to your SQL Server with user «xyz/ASPNET» — that’s the account your ASP.NET app is running under.

This account is not allowed to connect to SQL Server — either create a login on SQL Server for that account, or then specify another valid SQL Server account in your connection string.

Can you show us your connection string (by updating your original question)?

UPDATE: Ok, you’re using integrated Windows authentication —> you need to create a SQL Server login for «xyzASPNET» on your SQL Server — or change your connection string to something like:

connectionString="Server=.SQLExpress;Database=IFItest;User ID=xyz;pwd=top$secret"

If you have a user «xyz» with a password of «top$secret» in your database.

Aage's user avatar

Aage

5,8922 gold badges32 silver badges56 bronze badges

answered Apr 4, 2010 at 21:16

marc_s's user avatar

marc_smarc_s

729k174 gold badges1327 silver badges1455 bronze badges

7

  • Either: «xyzASPNET» is not a login (in sys.server_principals)
  • Or: «xyzASPNET» is set up but not mapped to a user in the database test (sys.database_principals)

I’d go for the 2nd option: the error message implies the default database is either not there or no rights in it, rather than not set up as a login.

To test if it’s set up as a login

SELECT SUSER_ID('xyzASPNET') -- (**not** SUSER_SID)

If NULL

CREATE LOGIN [xyzASPNET] FROM WINDOWS

If not NULL

USE test
GO
SELECT USER_ID('xyzASPNET')

If NULL

USE test
GO
CREATE USER [xyzASPNET] FROM LOGIN [xyzASPNET]

answered Apr 5, 2010 at 10:21

gbn's user avatar

2

I had this problem and what solved it for me was to:

  • Go to the Application pools in the IIS
  • Right click on my project application pool
  • In Process Model section open Identity
  • Choose Custom account option
  • Enter your pc user name and password.

answered May 14, 2015 at 8:10

ParPar's user avatar

ParParParPar

7,3077 gold badges43 silver badges55 bronze badges

1

For me the database was not created and EF code first should have created it but always endet in this error. The same connection string was working in aspnet core default web project. The solution was to add

_dbContext.Database.EnsureCreated()

before the first database contact (before DB seeding).

answered Feb 15, 2018 at 8:25

cyptus's user avatar

cyptuscyptus

3,3263 gold badges31 silver badges52 bronze badges

3

The best solution for the login problem is to create a login user in sqlServer. Here are the steps to create a SQL Server login that uses Windows Authentication (SQL Server Management Studio):

  1. In SQL Server Management Studio, open Object Explorer and expand the folder of
    the server instance in which to create the new login.
  2. Right-click the Security folder, point to New, and then click Login.
  3. On the General page, enter the name of a Windows user in the Login name box.
  4. Select Windows Authentication.
  5. Click OK.

For example, if the user name is xyzASPNET, then enter this name into Login name Box.

Also you need to change the User mapping to allow access to the Database which you want to access.

Community's user avatar

answered Jun 24, 2011 at 12:16

Rajeev's user avatar

RajeevRajeev

1011 silver badge2 bronze badges

Most times, it’s not a login issue, but an issue with creating the database itself. So if there is an error creating your database, it would not be created in the first place. In which case if you tried to log in, regardless of the user, login would fail. This usually happens due to logical misinterpretation of the db context.

Visit the site in a browser and REALLY read those error logs, this can help you spot the problem with you code (usually conflicting logic problems with the model).

In my case, the code compiled fine, same login problem, while I was still downloading management studio, I went through the error log, fixed my db context constraints and site started running fine….meanwhile management studio is still downloading

answered Mar 26, 2015 at 19:58

Justice O.'s user avatar

Justice O.Justice O.

1,21312 silver badges19 bronze badges

0

It also happen when you type wrong name of DB

ex : xxx-db-dev to xxx-dev-db

Sometime, it’s just a stupid mistake . I take about more than 1 hours to find out this :( because i just try alot of difficult thing first

answered Dec 20, 2017 at 7:14

Wolf's user avatar

WolfWolf

6,3222 gold badges28 silver badges25 bronze badges

1

The Issue

The error presents itself as a message similar to this:

Cannot open database «DATABASE NAME» requested by the login. The login
failed. Login failed for user XYZ.

  • The error cannot usually be rectified by a simple Visual Studio or full-computer restart.
  • The error can also be found as a seemingly locked database file.

The Fix

The solution is laid in the following steps. You will not lose any data in your database and you should not delete your database file!

Pre-requisite: You must have installed SQL Server Management Studio (Full or Express)

  1. Open SQL Server Management Studio
  2. In the «Connect to Server» window (File->Connect object explorer) enter the following:
    • Server type : Database Engine
    • Server name : (localdb)v11.0
    • Authentication : [Whatever you used when you created your local db. Probably Windows Authentication).
  3. Click «Connect»
  4. Expand the «Databases» folder in the Object Explorer (View->Object Explorer, F8)
  5. Find your database. It should be named as the full path to your database (.mdf) file
    • You should see it says «(Pending Recovery)» at the end of the database name or when you try to expand the database it won’t be able to and may or may not give you an error message.
    • This the issue! Your database has crashed essentially..
  6. Right click on the database then select «Tasks -> Detach…».
  7. In the detach window, select your database in the list and check the column that says «Drop Connections»
  8. Click OK.
  9. You should see the database disappear from the list of databases. Your problem should now be fixed. Go and run your application that uses your localdb.
  10. After running your application, your database will re-appear in the list of databases — this is correct. It should not say «Pending recovery» any more since it should be working properly.

The source of the solution: https://www.codeproject.com/Tips/775607/How-to-fix-LocalDB-Requested-Login-failed

answered Apr 27, 2017 at 21:04

Anton Lyhin's user avatar

Anton LyhinAnton Lyhin

1,9152 gold badges28 silver badges33 bronze badges

1

I tried to update the user, and it worked. See the command below.

USE ComparisonData// databaseName
EXEC  sp_change_users_login @Action='update_one', @UserNamePattern='ftool',@LoginName='ftool';

Just replace user('ftool') accordingly.

totymedli's user avatar

totymedli

29.2k22 gold badges130 silver badges164 bronze badges

answered Sep 18, 2013 at 7:17

shashank's user avatar

0

I had this problem when I created a WPF .NET Core + Entity Framework Core project and then cloning it on a a new laptop.

Using:

update-database

in the package manager console simply solved it.

To open package manager console go to:

Tools-> Nuget Package Manager -> Package Manager console

answered May 20, 2021 at 20:41

Daniel's user avatar

DanielDaniel

1632 silver badges10 bronze badges

I used Windows authentication to connect to local database .mdf file and
my local server was sql server 2014.
My problem solved using this connection string:

string sqlString = " Data Source = (LocalDB)\MSSQLLocalDB;" + "AttachDbFilename = F:\.........\myDatabase.mdf; Integrated Security = True; Connect Timeout = 30";

Machavity's user avatar

Machavity

30.7k27 gold badges91 silver badges100 bronze badges

answered Jun 28, 2016 at 14:34

Ehsan's user avatar

EhsanEhsan

212 bronze badges

1

In my case it is a different issue. The database turned into single user mode and a second connection to the database was showing this exception.
To resolve this issue follow below steps.

  1. Make sure the object explorer is pointed to a system database like master.
  2. Execute a exec sp_who2 and find all the connections to database ‘my_db’. Kill all the connections by doing KILL { session id } where session id is the SPID listed by sp_who2.
USE MASTER;
EXEC sp_who2
  1. Alter the database
USE MASTER;
ALTER DATABASE [my_db] SET MULTI_USER
GO

answered Sep 6, 2019 at 7:46

Krishanth Rajkumar's user avatar

I ran into this issue when attempting to write to the default database provided in the asp.net mvc template. This was due to the fact that the database hadn’t been created yet.

To create the database and make sure that it is accessible follow these steps:

  1. Open up the Package manager console in Visual Studio
  2. Run the command «update-database»

This will create the database an run all the necessary migrations on it.

answered Jan 22, 2020 at 2:07

GrantByrne's user avatar

GrantByrneGrantByrne

84010 silver badges21 bronze badges

I have not seen this mentioned in the previous issues, so let me throw out another possibility. It could be that IFItest is not reachable or simply does not exist. For example, if one has a number of configurations, each with its own database, it could be that the database name was not changed to the correct one for the current configuration.

answered Jan 13, 2014 at 16:40

demongolem's user avatar

demongolemdemongolem

9,42036 gold badges90 silver badges105 bronze badges

NB: If using a windows service to host the webservice.

You have to insure that your webservice is using the right Log on account to connect to SQL Server.

  • Open services(I assume the windows service has been install)
  • Right click on the service and goto properties.
  • Click on «Log On» Tab
  • Click on «This account» radio button
  • Click «Browse»
  • Enter Pc user name in Text Field and click «Check Name» Button to the right.
  • Click on text in Text Field, press «OK» button
  • enter login password and Apply

answered Jul 26, 2018 at 16:12

Goodwill Monoto's user avatar

Inspired by cyptus’s answer I used

_dbContext.Database.CreateIfNotExists();

on EF6 before the first database contact (before DB seeding).

answered Jun 17, 2019 at 18:01

Jesse Hufstetler's user avatar

If you haven’t created the database in your server you will get the same login error.Make sure that the database exist before you login.

answered Jun 21, 2019 at 6:26

AmirHossein Rezaei's user avatar

it’s not a login issue most times. The database might not have been created. To create the database, Go to db context file and add this.Database.EnsureCreated();

answered Feb 10, 2021 at 12:54

Gerald's user avatar

The best option would be to use Windows integrated authentication as it is more secure than sql authentication. Create a new windows user in sql server with necessary permissions and change IIS user in the application pool security settings.

answered Apr 4, 2010 at 21:24

Giorgi's user avatar

GiorgiGiorgi

30.3k13 gold badges89 silver badges125 bronze badges

0

I found that I also had to set the UserMapping option when creating a new login and this solved the problem for me. Hope that helps anyone that also found themselves stuck here!

Edit: Setting the login as db owner solved the next problem, too

answered Oct 26, 2012 at 15:22

DevDave's user avatar

DevDaveDevDave

6,66012 gold badges64 silver badges98 bronze badges

Some times this trouble may appear if you open this db in another sql server (as example, you launch sql managment studio(SMS) and add this db), and forget stop this server. As result — you app try to connect with user already connected in this db under another server. To fix that, try stop this server by Config. dispatcher sql server.

My apologies about bad english.
Kind regards, Ignat.

answered Dec 7, 2014 at 13:54

user3041948's user avatar

user3041948user3041948

1012 silver badges8 bronze badges

In my case the asp.net application can usually connect to database without any problems. I noticed such message in logs. I turn on the SQL server logs and I find out this message:

2016-10-28 10:27:10.86 Logon       Login failed for user '****'. Reason: Failed to open the explicitly specified database '****'. [CLIENT: <local machine>]
2016-10-28 10:27:13.22 Server      SQL Server is terminating because of a system shutdown. This is an informational message only. No user action is required.

So it seems that server was restarting and that SQL server whad been shutting down a bit earlier then ASP.NET application and the database was not available for few seconds before server restart.

Community's user avatar

answered Dec 3, 2016 at 21:00

Tomas Kubes's user avatar

Tomas KubesTomas Kubes

23.5k18 gold badges109 silver badges147 bronze badges

Even if you’ve set the login as DB owner and set the user mapping for the database that will use the login, check that the actual DB user (not just the login) has the role of ‘owner’.

answered May 5, 2017 at 6:29

Chris Halcrow's user avatar

Chris HalcrowChris Halcrow

28.4k17 gold badges173 silver badges203 bronze badges

In my case, I was running a Windows Service under «System» identity. The error was:

System.Data.SqlClient.SqlException (0x80131904): 
Cannot open database "MyDbName" requested by the login. The login failed.
Login failed for user 'MYDOMAINNAMEHOSTNAME$'.

The problem is that the error is very misleading. Even after I added ‘MYDOMAINNAMEHOSTNAME$’ login to the database, and granted this login sysadmin access and added a user for that login on my target database, and made that user dbowner, I was still getting the same error.
Apparently I needed to do the same for ‘NT AUTHORITYSYSTEM’ login. After I did that, I was able to login without a problem. I don’t know why the error message complains about ‘MYDOMAINNAMEHOSTNAME$’. I deleted that login and the corresponding user and everything still works.

answered Jul 23, 2019 at 20:24

Greg Z.'s user avatar

Greg Z.Greg Z.

1,32614 silver badges17 bronze badges

When using EF Code First, make sure the database exists. You could run the update-database command first.

Grigory Zhadko's user avatar

answered Jul 15, 2021 at 17:31

sinetemba's user avatar

If none of the above solution is working.

I encountered with the same error message but my issue was completely different. I had just restore my database and the database was in restoring mode. So if your database is in rstoring mode just apply following query.

RESTORE DATABASE MyDatabase
   FROM DISK = 'pathToYourDbBackupMyDatabase.bak'
   WITH REPLACE,RECOVERY

answered Sep 1, 2021 at 11:02

Rajon Tanducar's user avatar

I had this happen to me when I deleted the DB and forgot to recreate it. It happens sometimes, since Database folder needs refresh.

answered Nov 5, 2021 at 12:43

GeorgiG's user avatar

GeorgiGGeorgiG

1,0081 gold badge12 silver badges29 bronze badges

1

If you didn’t have any problems before and you get this error only in the package manager console, you don’t need to do anything special. Just open the sql server object explorer window and connect and run the command again in the console.

answered Jul 12, 2022 at 15:12

jafar's user avatar

jafarjafar

172 silver badges10 bronze badges

I experienced this same error but I didn’t need to create any password or username in sql. I just needed to fix my pyodbc.connect string.

'Driver={SQL Server};'
'Server=ExactServerName;'
'Database=ExactDatabaseName;'
'Trusted_Connection=yes;'

Once I passed it correct data it worked fine.

answered Apr 1 at 16:18

stdntuvmath's user avatar

Error Message

In ArcGIS Server Manager for the Microsoft .NET Framework, it is possible to create a Web application on a different Web server machine. This remote Web application may then be secured in Manager, with designated roles allowed access to the application. When the user logs in to the Web application, the browser may display an error.By default, a generic error is displayed, except when the browser is running on the Web server hosting the application. In the latter case, the error message displays. The error message may be along these lines:

"Cannot open database "<database>" requested by the login. The login failed. Login failed for user '<user name>'."

The <user name> is typically Network Service or ASPNET.

Cause

This error may occur when the user store configured for the ArcGIS Server is in Microsoft SQL Server, though it may also occur with a user store in a custom provider. The cause is that the user store defined in the Manager application is not accessible to the Web application that is running on the remote IIS Web server.

Specifically, the problem may be due to the machine name running SQL Server not being specified adequately, or incorrect permissions for the account accessing the SQL Server or custom provider.

Solution or Workaround

The resolution may require one or both of the following two steps:

  • Correcting the machine name or location information for the database.
  • Ensuring valid permissions for the account running the application.

The steps below address the problem for SQL Server. For similar problems when using a custom provider, it is necessary to perform comparable steps for a custom provider, such as configuring the provider location and permissions.

  1. The first cause of the error may be that the machine name of the SQL Server needs to be specified so that the remote machine can find it. To address this issue:
    1. Log in to ArcGIS Server Manager.
    2. Click Security — Settings, and click Configure.
    3. In the Security wizard, the first panel should be set to SQL Server. Click Next.
    4. In the Specify SQL Server panel, examine the value for the Server. It should specify the server name so that the remote machine can find it. The name should not use «.» or «localhost». If necessary, verify that the remote Web server hosting the application can access the SQL Server using the name (or IP address). If the SQL Server machine name was already set to a name that the remote Web server can use for access, skip to step 2 below. Otherwise, change the name, if necessary, to use the SQL Server machine name or IP address.
    5. If the SQL Server name has been modified, click Connect, and complete the wizard to save the updated settings.
    6. Go to the Applications tab, and for the remote Web application, click the Permissions button.
    7. In the Permissions dialog box, click Save (changes can be made to permissions, but it is not necessary). This re-writes the Web application’s configuration with the updated SQL Server name.
    8. Open a browser to the remote Web application and log in. If it is possible to successfully log in and use the application, skip the rest of the steps below. If a permissions error displays, continue with step 2.
  2. The connection to the SQL Server database must be configured to allow the Web application to access the database.

    The approach illustrated here is to use a SQL login to connect to the database rather than Windows authentication. Follow the directions below to change the authentication for the Web application to use a SQL login for the Web application’s connection.

    1. Open SQL Server Management Studio and connect to the SQL Server instance. For SQL Server Express, if necessary, install SQL Server Management Studio Express.
    2. For SQL Server Express, allow SQL logins. To do this, right-click the server (<servername>SQLEXPRESS) in the left-hand tree, and click Properties. In the Properties window, click the Security page link. In the security panel, click the option under Server authentication for SQL Server and Windows Authentication mode. Click OK to save the settings and close the Properties dialog box.
    3. Add a new SQL login by expanding the Security folder and clicking the Logins folder. Right-click the Logins folder and click New Login. In the dialog box that opens, enter a name for the new login (e.g., AGSApplications). Click the option for SQL Server authentication, enter a password, and confirm the password.
    4. In the same new-login dialog box, click the User Mapping page link. Under the Users mapped to this login, click the check box next to the database that contains the users for the ArcGIS Server system. Make sure the database is highlighted in the dialog box, then, under the Database role membership for: <database>, check the db_owner role. Click OK to create the login and its role. Close SQL Server Management Studio.
    5. Log in to ArcGIS Server Manager > Security > Settings > Configure.
    6. In the Security wizard, click SQL Server for the user location, if necessary, and click Next.
    7. In the Specify SQL Server panel, enter the SQL Server name, using the server name rather than «.» or «localhost». Click Connect to connect to the SQL Server.
    8. In the lower portion of the dialog box that displays, uncheck the Use Trusted Connection checkbox. Enter the login name and password for the SQL login created above. Select the database from the Use existing database drop-down menu. Click Next and finish the wizard as directed.
    9. Go to the Applications tab, and for the remote Web application, and click the Permissions button.
    10. In the Permissions dialog box, click Save (changes to permissions can be made, but it is not necessary). This re-writes the Web application’s configuration with the updated SQL Server login.
    11. Open a browser to the remote Web application and log in. Logging in and using the application should be successful. If any permissions error occur, recheck the settings for the SQL login and Manager configuration.

RRS feed

  • Remove From My Forums
  • Question

  • Received the following:

    Cannot open database «Databasename» requested by the login.  The login failed.  Login failed for user ‘ComputerUser’.

    The following is to be found in the constructor for the class that is attempting to create a database by running a script:

    txtConnString.Text = "Data Source=.\SQLEXPRESS;" +
        "Initial Catalog=MyTrLog1;Integrated Security=True";
    
    

    The event handler to create the database has the following code:

    if (File.Exists(txtScript.Text))
            {
              string script = File.ReadAllText(txtScript.Text);// file.OpenText().ReadToEnd();
              SqlConnection conn = new SqlConnection(txtConnString.Text);
              conn.Open();
              Server server = new Server(new ServerConnection(conn));
              server.ConnectionContext.ExecuteNonQuery(script);
              conn.Close();
            }
    

    Running the code in debugger mode shows that the server was found on the developer computer which uses Vista.  The code which is in try/catch blocks runs without a problem.  But when I run the .msi on a target computer (XP Pro) and get to
    the part to create the database, nothing seems to happen when I click Create.

    I can start the program after the installation but trying to access any part of the database yields the message above.

    I am about ready to give up on sql server and redo the whole program using some alternative.  XML files perhaps?  Or is VS2010 more user-friendly when it comes to interfacing with the server?  I am currently using VS2005.

    Thanks for your help.

    Ruel

    • Moved by
      SamAgain
      Tuesday, July 20, 2010 7:33 AM
      (From:.NET Base Class Library)

Answers

    • Marked as answer by
      RueSam
      Friday, July 23, 2010 1:14 AM

All replies

  • Is MyTrLog1 the database (catalog) that you’re trying to create?  If so, you cannot open it until after it’s created.  You need to use a connection string without a catalog — it’ll get set to the default for the user which is usually ‘master’.

  • Is MyTrLog1 the database (catalog) that you’re trying to create?  If so, you cannot open it until after it’s created.  You need to use a connection string without a catalog — it’ll get set to the default for the user which is usually ‘master’.

    Thanks for the help.

    I tried the following:

    //Constructor
    txtConnString.Text = "Data Source=.\SQLEXPRESS;" +
            //"User Instance=True;" + 
            //"AttachDbFilename=|DataDirectory|\MyTrLog1.mdf;" + //Initial Catalog=MyTrLog1;
            "Integrated Security=True;";
    
          txtScript.Text = Path.Combine(Environment.GetFolderPath(
            Environment.SpecialFolder.ProgramFiles), 
            @"C & R Management Services, IncMyTruckLogCreateDatabase.sql");
    
    //Event handler
    try
          {
            if (File.Exists(txtScript.Text))
            {
              string script = File.ReadAllText(txtScript.Text);// file.OpenText().ReadToEnd();
              SqlConnection conn = new SqlConnection(txtConnString.Text);
              //conn.Open();
              Server server = new Server(new ServerConnection(conn));
              server.ConnectionContext.ExecuteNonQuery(script);
              //conn.Close();
            }
          }
          catch (SqlException sqx)
          {
            MessageBox.Show(sqx.Message);
          }
          catch (Exception ex)
          {
            MessageBox.Show(ex.Message);
          }
    
    

    And I got the following:

    An exception occurred while executing a Transct-SQL statement or batch.

    I am inclined to think that it is not the CreateDatabase.sql file itself that is causing this error message since I miraculously created the .mdf and .log files in a previous experiment yesterday — problem is that I still could not access the database
    when I started the program; that success occurred by compiling the create_database.exe and copying it to the target computer’s installed files directory.

    I subsequently deleted the databases created (on the target computer of course) to duplicate the success with the create_database.exe file being incorporated as part of the MyTruckLog.msi program.  No luck.  Since then I have no success with recompiling
    create_datase.exe and copying it to the target computer.

    Ruel

  • Sounds like it could be a permissions issue.  What was the full detail on the exception including the stack trace and inner exceptions if any?

    Try running the installation program as an administrator.

  • Sounds like it could be a permissions issue.  What was the full detail on the exception including the stack trace and inner exceptions if any?

    Try running the installation program as an administrator.

    Got the same message running as administrator.

  • What was the full detail on the exception including the stack trace and inner exceptions if any?

  • What was the full detail on the exception including the stack trace and inner exceptions if any?

    Only «An exception occurred while executing a Transct-SQL statement or batch.» appears in the message box on the target computer. 

    Which utility should I use on the target computer?

    Looking at the error log in \MSSQLLOG shows:

     «Dedicated administrator connection support was not started because it is not available on this edition of SQL Server.»

    «Login failed for user ‘ ‘.  The user is not associated with a trusted SQL Server connection.»

    Seems the latter sentence may be my problem?

  • Hi,

    Please try changing the Authentication mode for that sql server to Mixed Authentication mode so that windows authentication will be enabled.

    [Please mark the post as answer if it answers your question]

    Thanks & Regards,

    Sai Pavan

  • Hi,

    Please try changing the Authentication mode for that sql server to Mixed Authentication mode so that windows authentication will be enabled.

    [Please mark the post as answer if it answers your question]

    Thanks & Regards,

    Sai Pavan

    Sai,

    I think you may be pointing me in the right direction.

    If we are talking about sql server on the target computer, I would have to use code somewhere in the installation process to add the authentication mode to the registry — I presume before running the script to create the database? 

    And how does one handle the sa password on the target computer since a password is required with mixed mode authentication?

    Ruel

  • Hi RueSam,

    I did some analysis and found out that there are only two logins available by default on SQLEXPRESS viz., sa and BuiltInUsers and sa is disabled and BuiltInUsers is not a sysadmin which means that you locked yourself out of the system. So you will not
    be able to execute any commands on the SQLEXPRESS. In order to resolve this issue run the SSMS using «Run as Administrator» and then connect to the SQLEXPRESS instance and enable the mixed mode authentication and sa accounts.

    In order to programatically do this

    First instantiate a cmd with adminstartor privileges using the following code can be used as guidance

    MyStartInfo.UseShellExecute = true;           

    MyStartInfo.Verb = «runas»;
    MyStartInfo.Arguments = «/env /user:» + «Administrator» + » cmd»;

    Now start the process (cmd with admin privileges) and run the following commands in it

    osql -S .SQLEXPRESS -E -Q «ALTER LOGIN sa ENABLE»

    osql -S .SQLEXPRESS -E -Q «ALTER LOGIN sa WITH PASSWORD = ‘abcd#123′»

    net stop MSSQL$SQLEXPRESS

    net start MSSQL$SQLEXPRESS

    Now you will be able to login using sa account. For this to work the authentication mode has to be in «Mixed Mode»

    [Please mark the post as answer if it answers your question]

    Thanks & Regards,

    Sai Pavan

    • Marked as answer by
      RueSam
      Friday, July 23, 2010 1:14 AM
  • Received the following:

    Cannot open database «Databasename» requested by the login.  The login failed.  Login failed for user ‘ComputerUser’.

    Hi Ruel,

    The error is caused by the login does not have sufficient permissions on the database. Your connection string uses Windows Authentication, so the current Windows account will be used to connect to SQL Server.

    You can refer to the following links to grant permissions to the login, which is ‘ComputerUser’ in your case.

    http://forums.asp.net/t/1473123.aspx

    SQL SERVER – FIX : ERROR : Cannot open database requested by the login. The login failed. Login failed for user ‘NT AUTHORITYNETWORK SERVICE’.

    As the application needs to be deployed on multiple computers, this problem may occur at times. I suggest you use a feature called user instance to attach and connect to the SQL Server database.

    User instance is a feature of SQL Server Express Edition and is not supported by other editions of SQL Server (such as Developer or Enterprise). Attaching the database files with user instance is easy for deployment. It allows users who are not administrators
    on their local computers to attach and connect to SQL Server Express databases.

    If we want to work with SQL Server Express user instance, we need to put the database files in the “App_Data” folder and use a connection string like follows:

    Data Source=.SQLExpress;integrated security=true;attachdbfilename=|DataDirectory|Test.mdf;user instance=true

    For more information, I would suggest you refer to the documents below:

    SQL Server 2005 Express Edition User Instances
    http://msdn.microsoft.com/en-us/library/bb264564.aspx

    Working with User Instances
    http://msdn2.microsoft.com/en-us/library/ms254504.aspx

    We can also embed SQL Server Express within our application so that SQL Server Express will be installed with our application. Please see:

    Embedding SQL Server Express into Custom Applications
    http://msdn.microsoft.com/en-us/library/bb264562(SQL.90).aspx

    Configuring SQL Express During Installation
    http://blogs.msdn.com/b/sqlexpress/archive/2006/09/20/configuring-sql-express-during-installation.aspx


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.

    Thank you very much.  Your links led me to the MS Topic «Connecting to SQL Server Express User Instances (ADO.NET)» which in turn made me see the error I was making all along:  The name of the data file was MyTruckLog.mdf whereas the name of
    the database was MyTrLog1.  Even then I nearly went wrong before realizing that I had to delete the old log file in the target directory!

    Thanks once more.

    Ruel Samuels

  • Hi RueSam,

    I did some analysis and found out that there are only two logins available by default on SQLEXPRESS viz., sa and BuiltInUsers and sa is disabled and BuiltInUsers is not a sysadmin which means that you locked yourself out of the system. So you will not
    be able to execute any commands on the SQLEXPRESS. In order to resolve this issue run the SSMS using «Run as Administrator» and then connect to the SQLEXPRESS instance and enable the mixed mode authentication and sa accounts.

    In order to programatically do this

    First instantiate a cmd with adminstartor privileges using the following code can be used as guidance

    MyStartInfo.UseShellExecute = true;           

    MyStartInfo.Verb = «runas»;
    MyStartInfo.Arguments = «/env /user:» + «Administrator» + » cmd»;

    Now start the process (cmd with admin privileges) and run the following commands in it

    osql -S .SQLEXPRESS -E -Q «ALTER LOGIN sa ENABLE»

    osql -S .SQLEXPRESS -E -Q «ALTER LOGIN sa WITH PASSWORD = ‘abcd#123′»

    net stop MSSQL$SQLEXPRESS

    net start MSSQL$SQLEXPRESS

    Now you will be able to login using sa account. For this to work the authentication mode has to be in «Mixed Mode»

    [Please mark the post as answer if it answers your question]

    Thanks & Regards,

    Sai Pavan

    Thank you for your input Sai.  Please see my reply to Jian Kang.  Ruel

Hello I am trying to use SQL Authentication to connect to a database . I am having extreme difficulties and my searches so far couldn’t help me solve the problem.

I Enabled the SQL Authentication through SQL SERVER MANAGEMENT STUDIO and enabled
sa and set a simple password for it.(under .sqlexpress — i mean my server-name is ).
 Now I can Successfully log in to the database by sa and its password from
SQL SERVER MANAGEMENT STUDIO but when i try to do so from my application it fails with this error message :

//Cannot open database "dbNegin" requested by the login. The login failed. Login failed for user 'sa'.

I need to say that i changed the database owner to sa as well, yet i get this error!!

How can i solve this now? :(

By the way this is the connection string used in my application to connect to the database :

    string sqlconstring = @"Data Source=.sqlexpress;User ID=sa;Password=123456;Initial Catalog=dbNegin";

My data base is attached by the way (its located in the address below )

   " D:TestDbDebugdbNegin.mdf"

It is just driving me insane , I have tested all i could find but nothing seems to work :(

Please somebody help me

January 4, 2016

One of the trickiest problems I encountered when I was just starting ASP.NET web development was debugging issues with my web application connecting to SQL server, especially when connecting to a local instance of SQL Server.

Often the error messages related to these issues were not quite clear or ended up sending me on a wild goose chase.

To that end, here’s a list of a few error messages I’ve often encountered and how to solve them:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 — Could not open a connection to SQL Server)

This is the most generic and most frustrating of the errors. There are a couple possible solutions:

First, double-check the server name in your connection string. In other words, let’s say your connection string is the following:

Server=ServerName;Database=DatabaseName;

The error above can occur if something has gone wrong with the Server=ServerName piece. Check for the following:

  • Server name is spelled correctly
  • Server port number (if applicable) is correct
  • Application pool account has permissions to send requests to the server

If you are connecting to a local instance, this will likely be Server=(local). However, it’s also possible your local instance could have a different name (e.g. (local)SQLEXPRESS or (local)MSSQLSERVER).

Second, ensure that the instance of SQL server has not stopped.

You can do this by accessing the “Services” list in Windows. In Windows 10, this is simply a tab on the Task Manager:

Top portion of the Task Manager in Windows 10, with the Services tab selected

(In earlier versions of Windows go to “Run” and enter “services.msc”.)

Once you have accessed the list of Services, look for your instance of SQL server in the list (probably named MSSQLSERVER or MSSQL$SQLEXPRESS) and ensure that is “Running.” If it has stopped, simply right-click the service and click “Start”:

SQL Server instance selected in list of Services with mouse hovering over option to start service

Login failed for user ‘’

Login failed for user ‘’.

The important bit to notice here is that there is no username displayed, which means no username is being sent to SQL Server for authentication. So, with that in mind:

First, did you intend to send over a username and password but forgot?

Server=ServerName;Database=DatabaseName;User Id=Username;Password=Password;

Second, did you intend to use integrated security (Windows Authentication) but didn’t specify that?

Server=ServerName;Database=DatabaseName;Integrated Security=SSPI;

(In most cases, this is probably what you want: this setting allows your web application to use Windows Authentication to authenticate with your application pool’s account)

Cannot open database “DatabaseName” requested by the login

Cannot open database “DatabaseName” requested by the login. The login failed. Login failed for user ‘DOMAINUsername’.

This is another generic error with a couple solutions:

First, double-check the database name in your connection string is spelled correctly.

Second, ensure your website’s domain account has permissions to access the database:

Screenshot of SQL Server Management Studio with the users assigned to a particular database displayed

Login failed for user ‘DOMAINUsername’

Login failed for user ‘DOMAINUsername’.

This is similar to the error above. The slight difference, however, is that there is no “Cannot open database” alongside this error message.

This means that your website’s application pool account does not have permissions to access the database instance itself (not the actual database, but the instance on which the database is hosted):

Screenshot of SQL Server Management Studio with the users assigned to a particular SQL server instance displayed

Возможно, вам также будет интересно:

  • Ошибка cannot load library client
  • Ошибка cannot open 7zxa dll
  • Ошибка cannot load asacpi dll
  • Ошибка cannot load android system
  • Ошибка cannot launch game unless steam is running

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии