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

1

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

Herearemycodes:

  • IwenttotheProgram.csfileinVisualStudioandaddedthefollowinglines:
  •   

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

  • 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";

    The bold part 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 the lesson, with the same codes, it worked.

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

        
    asked by anonymous 20.07.2017 / 01:08

    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'). So for your connection to work, Visual Studio must be open. It may be the problem if you are running the compiled executable directly from Windows.

    Verify that the .mdf file 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' should exist within this folder:

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

    If it still does not work

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

    Good luck!

        
    20.07.2017 / 23:44