Wednesday, March 28, 2012

How to connect to SQL server 2005 from C# after default installation?

Hi everyone,

I just installed Visual Studio 2005 and SQL Server 2005. However, I`m not able to connect to the database.

When running this C# code, I get a SqlException.

using System; using System.Data; using System.Data.SqlClient; class Program {
static void Main(string[] args) {
SqlConnection connection = new SqlConnection(); connection.ConnectionString = "Data Source=(local)\\sqlexpress;Initial Catalog=X;Integrated Security=True;"; connection.Open(); connection.Close();
}
}

I get the following error message:

Cannot open database X requested by the login. The login failed.
Login failed for user Y.

Can anyone tell me how to connect to sql server 2005 after default installation? Any help would be appreciated! :-)

Jan

Most likely your user ID does not exist in a list of the logins for the database. You need to grant an access for your Windows account to the database. Check next links with some info

http://support.microsoft.com/kb/325003/en-us#XSLTH4213121122120121120120

http://support.microsoft.com/kb/240872/en-us

|||Thx, my program runs!

I executed the following command (in VS Command Prompt) to add my windows account to the list of database accounts.

C:\>osql -E -S (local)\sqlexpress
1> EXEC sp_grantlogin 'machine_name\user_name'
2> go
1> exit

No comments:

Post a Comment