Spider man
Spider man

Reputation: 3330

Error while connecting to sql through windows authentication

I am using the following code to connect to sql throgh windows authentication.

string connctionstring = "connectionString={0};Database={1};Integrated Security=SSPI;";
string _connctionstring = string.Format(connctionstring, datasource, initialCatalogue);
SqlConnection _connection = new SqlConnection(_connctionstring);
_connection.Open();

But i am getting the following error. Help please.I am able to login through sql server.

enter image description here

Upvotes: 1

Views: 74

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127603

While Peyman's answer does cover the basic issue (connectionString is not a valid key for the string) a better solution is to use a SqlConnectionStringBuilder, this will also help you do proper escaping if you have odd characters in your string (for example if your database name contained a space)

var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = datasource;
scsb.InitialCatalog = initialCatalogue;
scsb.IntegratedSecurity = true;

//You also really should wrap your connections in using statements too.
using(SqlConnection connection = new SqlConnection(scsb.ConnectionString))
{
    connection.Open();
    //...
}

Upvotes: 2

Peyman
Peyman

Reputation: 3136

The connection string format is not correct Change to this:

string connctionstring = "Data Source={0};Database={1};Integrated Security=SSPI;";

Or

string connctionstring = "Server={0};Database={1};Integrated Security=SSPI;";

Upvotes: 5

Related Questions