Search code examples
sqlvisual-studio-2013sqlconnection

Trouble establishing connection to Local SQL database


Simply trying to find out the correct syntax for my connection string. Before anyone asks, yes I did look at other SO answers, and no they did not work for me. Here a couple of attempts I made from looking at other SO questions like the one I am asking

Server=(local);Database=SalesOrdersExample;Integrated Security= true
Data Source=(local);Database=SalesOrdersExample;Integrated Security=SSPI
Server=.\\SQLEXPRESS;Database=SalesOrdersExampleDataSet;Integrated Security=true

None of them worked (I have a Console.WriteLine("test"); thrown in there and it works up until I try conn.Open() (opening the connection to database) so I'm assuming that it must be my connection string since nothing gets written after conn.Open())

Console.WriteLine("test"); // works

SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=SalesOrdersExampleDataSet;Integrated Security=true");

Console.WriteLine("test"); // works         
conn.Open();

Console.WriteLine("test"); // does not work

So some information about the database is that it's local under my 'Data Connections' in my Server Explorer. I also have the .xsd file in my project so I have linked the Data Set to the current project I am on. Here is a picture representation to confirm that I have both the Data Connection and the Data Set.

EDIT: SO does not allow me to post pictures until I have 10 rep so here is direct link to picture:

DB Screenshot

Any help is appreciated thank you.


Solution

  • Visual Studio comes with LocalDB database, which is not exactly SQL Server Express database.

    Try something like this:

    Server=(localdb)\v11.0;Integrated Security=true;
    

    or

    Data Source=(LocalDB)\v11.0; AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf; InitialCatalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True
    

    If using in c# code, you can use @ to avoid problems with backslash characters:

    SqlConnection conn = 
       new SqlConnection(@"Server=(localdb)\v11.0;Integrated Security=true;");