1

I'm making a C# application that uses SQL Server 2008 R2 Express on Windows 7 64bit. The problem I'm facing is I can't connect to my database because my connection string is wrong. I'm using a .udl file to make the connection string and this is what it gave me:

Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Restorant;
DataSource=.\SQLEXPRESS

This connection string is creating an error that says that there is an unrecognized escape value. I tried to change my data source to (local), since my friends said it works on their projects, but I couldn't connect because of an unknown instance name error.

Is there any way other for me to connect to my database?

Walter
  • 2,540
  • 2
  • 30
  • 38
  • for future reference Sandy when ever you have a return character in a string`\` you should always use the `@` symbol otherwise in C# you need to use `\\` – MethodMan Jan 06 '13 at 16:50

3 Answers3

3

In C# the character \ is considered the first char in an escaping sequence.
Because the \S of your Data Source=.\SQLEXPRESS is not recognized as a valid escape sequence you get the error.

So you need to construct your connection string prefixing it with the character @ or double the escaping character \\ See Working With Strings for the explanation of the @ character

string conString = @"Integrated Security=SSPI;Persist Security Info=False;" + 
                   @"Initial Catalog=Restorant;Data Source=.\SQLEXPRESS";

Remember to make more than one string verbatim with this method if you have to.

Also note the little error in the Data Source part of your connection string. It needs a space between the Data and Source. See connectionstrings.com

VisualMelon
  • 662
  • 12
  • 23
Steve
  • 213,761
  • 22
  • 232
  • 286
1

Right now your connection string is trying to escape S e.g. .\S. Change to this

//double the backslash to escape the slash
string connectionString = "Integrated Security=SSPI;Persist Security Info=False;
          Initial Catalog=Restorant; Data Source=.\\SQLEXPRESS";

OR

//precede the string with @
string connectionString = @"Integrated Security=SSPI;Persist Security Info=False;
          Initial Catalog=Restorant; Data Source=.\SQLEXPRESS";  
codingbiz
  • 26,179
  • 8
  • 59
  • 96
0

Try changing the datasource name to datasource Data Source=localhost\SQLExpress

Srinivas
  • 1,063
  • 7
  • 15