C# BD . mdf connection string

Asked

Viewed 492 times

1

Good evening, you guys, I have a database . mdf in a Windows Forms and want to make the connection string of it, can anyone help me? My version of Visual Studio is 2015 and the file is: C:Documents Visual Studio 2017 Projects Projects Final Work POO Final Work POO BD.mdf

1 answer

1

You can get the connection through the window Server Explorer.

In Server Explorer, click on Connect to database. Then choose the option Microsoft SQL Server Database File (Sqlclient) and then select the . mdf file you want. Fill in the necessary steps.

After adding the database that will appear in Data Connections inside the Server Explorer, right-click on the Data Connection and finally on Properties.

Inside the window Properties, there is a property called Connection String and that’s the connection you have to use to access the database.

I recommend placing this connection in a Resource.

  • I still can’t do it, you’re making a mistake on the bars:

  • The code is: Sqlconnection connection = new Sqlconnection("Data Source=(Localdb) Mssqllocaldb;Attachdbfilename= C: Users Tiago Documents Visual Studio 2017 Projects Projects Final Work POO Final Work POO BD.mdf";Integrated Security=True;Connect Timeout=30);

  • Try putting a @ before the string. That is: @"Data Source=(Localdb) Mssqllocaldb;Attachdbfilename= C: Users Tiago Documents Visual Studio 2017 Projects Projects Final Work POO Final Work POO BD.mdf"

  • If it doesn’t work it puts a second backlash on each backlash: "Data Source=(Localdb) Mssqllocaldb;Attachdbfilename= C: Users Tiago Documents Visual Studio 2017 Projects Projects Final Work POO Final Work POO BD.mdf";Integrated Security=True;Timeconnect Out=30);

  • This is because in C# backlash is an escape character in strings. To use backlash in strings use one of these two solutions.

  • using the connection string I came across the error: "An Attempt to attach an auto-named database for file C: Users John Documents visual studio 2010 Projects PAS bin Debug//Pataddsys.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is Located on UNC share." Obs: the path is fictitious.

Show 1 more comment

Browser other questions tagged

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