j.sinjaradze
j.sinjaradze

Reputation: 155

Can't connect Visual Studio to SQL Server database

I use Visual Studio 2017, I connected to my database from Server Explorer:

here it is.

Then I added SQL connection:

var constring = @"Data Source=JSINJARA\SQLEXPRESS,Database=box,Integrated Security=SSPI";
SqlConnection con = new SqlConnection(constring);

But when I try to open connection I get the following exception:

exception

What can be the problem?

Upvotes: 2

Views: 4015

Answers (3)

SᴇM
SᴇM

Reputation: 7213

Better add it to [app/web].config file and get it using ConfigurationManager.
It's should look something like this:

Config file:

<connectionStrings>
    <add name="ConnectionStringName" connectionString="Data Source=<<Server>>;Initial Catalog=<<DBName>>;User=<<User>>;Password=<<Password>>;"/>
</connectionStrings>

C#:

string connectionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
using(SqlConnection con = new SqlConnection(connectionString))
{
    //Your code goes here
}

Upvotes: 2

lapsick
lapsick

Reputation: 53

Try to set Integrated Security=True in connection

Upvotes: 0

Uwe Keim
Uwe Keim

Reputation: 40756

Use ; (semicolon) instead of , (comma) in the connection string.

E.g.

var constring = @"Data Source=JSINJARA\SQLEXPRESS;Database=box;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(constring);

See the Connection Strings website for many examples.

Upvotes: 2

Related Questions