Search code examples
sql-servervisual-studiodatabase-connectionconnection-string

Type address in data source in Visual Studio


I have some problem about type in connection string.

When I type my server address like this in C#:

string connection = "
Data source=./server ;
Initial Catalog=myDataBase;
User ID=sa;
Password=myPass
"

it doesn't work and doesn't find my server.

I checked my address in SQL Server Management Studio, and I saw it is .\my server

Yes it using ( \ ) . not ( / ) .

But when I am trying to type ( \ ) , it doesn't work in Visual Studio

I can't show my table :(


Solution

  • If you want to define a connection string as string literal in your C# code, you need to either duplicate the backslash:

    string connection = "Data source=.\\myserver;Initial Catalog=myDataBase;User ID=sa;Password=myPass"
    

    or you need to use a "here string" (the leading @) - then a single backslash will do:

    string connection = @"Data source=.\myserver;Initial Catalog=myDataBase;User ID=sa;Password=myPass"
    

    But yes - to separate machine name (.) from the instance name (myserver), SQL Server does in fact use backslash - not forward slash.

    See loads of samples and explanations of all the various settings you can define in your connection strings at connectionstrings.com