Error connecting to database [WinForm/C# / SQL Server]

My C # course teacher taught us a new technique today, one does not need to inform the ConnectionString itself, the program would go to the document folder and take the file .mdf (SQL Server) and would open the connection with it, but I have been presenting the following error:

Mistake I had

These are my Codes:

  1. I went to the Program.cs of the file in Visual Studio and accreted the following lines:

String x = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); AppDomain.CurrentDomain.SetData ("DataDirectory", x);

  1. in the class that stores the ConnectionString, I put the following line:

Public static string ConnectionString = @ " Data Source=(LocalDB) \ V11.0;AttachDbFilename=|DataDirectory|/baseFarmaciaZyX.mdf ; Integrated Security=True; Connect Timeout=30";

A part in bold would be the directory of the mdf file, which is picked up by the "DataDirectory".

I would like to know what happened, since when it was tested during class, with the same codes, it worked out.

(the file .mdf is in My "Documents" folder)

Author: Alan Jantz, 2017-07-19

1 answers

Ensure that the LocalDb instance is running

Visual Studio automatically uploads a local instance of SQLServer express (indicated in connectionString by 'LocalDB'). So for your connection to work, Visual Studio must be open. It can be the problem if you are running the compiled executable straight from Windows.

Verify that the file .mdf exists in the directory.

Environment.SpecialFolder.MyDocuments represents the 'My Documents' folder in Windows. But to ensure check the result of the expression below in your code (via debugging or printing to the console). The archive ' baseFarmaciaZyX.mdf ' must exist inside this folder:

string x = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 

If it still doesn't work

I suggest you follow instructions from the screen whose print you showed in the question. Many things can go wrong in a connection to a DB.

Good luck!

 0
Author: Genos, 2017-07-20 21:44:50