-2

New to using SQL Server inside of Visual Studio.

I am trying to create a portable program that will read in a CSV file and insert the data into a database.

I have created the database and added the .mdf file to my solution. However I cannot for the life of me figure out how to create a SqlConnection to said database.

The error I get is:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.

The database is named testdb.mdf and here is a snippet of the code I have tried:

openCon = new SqlConnection();
openCon.ConnectionString = "Data Source=(LocalDB)\v11.0;" +
                           "AttachDbFilename=" +
                            AppDomain.CurrentDomain.BaseDirectory + 
                           "testdb.mdf;" +
                           "Integrated Security=True";
openCon.Open();

I still receive the error after having tried the "duplicate post solution":

openCon.ConnectionString = "Data Source=.\\SQLEXPRESS;" +
                           "AttachDbFilename=" + AppDomain.CurrentDomain.BaseDirectory + "Encounter.mdf;" +
                           "Integrated Security=True";
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    Whats the error you are having? – litelite Aug 03 '17 at 19:11
  • Possible duplicate of [How do I connect to an MDF database file?](https://stackoverflow.com/questions/8926512/how-do-i-connect-to-an-mdf-database-file) – JeffUK Aug 03 '17 at 19:16
  • A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. – Bud Jameson Aug 03 '17 at 19:17
  • Do a simple google search on C# connection string in App.Config – MethodMan Aug 03 '17 at 19:21
  • See [Database ConnectionStrings](http://www.dofactory.com/reference/connection-strings) – Nikhil Vartak Aug 03 '17 at 19:23
  • I have updated my code to reflect you guys' suggestions, however I am still getting an error. – Bud Jameson Aug 03 '17 at 19:35
  • The same error? – JeffUK Aug 03 '17 at 19:40
  • @JeffUK Yes, I have updated the question to reflect both attempts. I have also tried obtaining the connection string from the properties of my .mdf and that has resulted in the same error as well. – Bud Jameson Aug 03 '17 at 19:41

1 Answers1

1

Figured it out. I was being an idiot and not escaping the '\' before the v11.0.

Thanks all!

openCon = new SqlConnection("Data Source=(LocalDB)\\v11.0;" +
                                       "AttachDbFilename=" + AppDomain.CurrentDomain.BaseDirectory + "Encounter.mdf;" +
                                       "Integrated Security=True");