Error when connecting to database [Winform/C#/SQL Server]

Asked

Viewed 213 times

1

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

Erro que eu tive

These are my codes:

  1. I went to the Program.Cs file in Visual Studio and added the following lines:

string x = Environment.Getfolderpath(Environment.SpecialFolder.Mydocuments); AppDomain.CurrentDomain.SetData("DataDirectory", x);

  1. In the class that stores 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";

The bold part would be the mdf file directory, which is picked up by "Datadirectory".

I’d like to know what happened, since when you were tested during class with the same codes, it worked.

(The file . mdf is in my folder "Documents")

1 answer

0


Ensure that the Localdb instance is running

Visual Studio automatically raises a local instance of Sqlserver express (Indicated in connectionString by 'Localdb'). Therefore for your connection to work, Visual Studio must be open. It may be the problem if you are running the compiled executable straight from Windows.

Check 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 Debug or printing to the console). The file 'baseFarmaciaZyX.mdf' must exist inside this folder:

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

If it doesn’t work yet

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

Good luck!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.