0

I'm trying to connect a table database I created within Visual Studio and used the connection string, but keep getting a bunch of errors? I need to do this multiple times but can't even get the first one to work + im not sure what's wrong

screenshot

this is the line of code I've used:

CSharp SqlConnection Con = new SqlConnection(
    @"Data Source=(LocalDB)\MSSQLLocalDB;
    AttachDbFilename="C:\Users\scara\Documents\nea2022 database.mdf";
    Integrated Security=True;
    Connect Timeout=30");

I've connected through the tools tab and "connect to database" and it said that it was successful, so I'm really not sure ://

6
  • 2
    Why not upload images of code/errors when asking a question? Commented May 8, 2022 at 15:20
  • "I'm trying to connect...... and it said that it was successful" Please make yourself clear, do you try to connect or was it successful ? Commented May 8, 2022 at 15:23
  • You're getting various syntax errors because you are not quoting quotes correctly. Commented May 8, 2022 at 15:28
  • 2
    AttachDbFilename is a really bad idea, it will cause copies to be made of your database, which are deleted when you close the connection. Just attach your database normally. Also you should keep your connection string in a settings file, which would have prevented this error in the first place Commented May 8, 2022 at 15:28
  • @Charlieface ohh, how would i store the connection string in a settings file? ive only really just started using sql servers and am just trying to follow a video right now Commented May 8, 2022 at 15:39

2 Answers 2

2

You should escape the inner quotes inside the connection string.

Use double quotes, for example:

CSharp SqlConnection Con = new SqlConnection(
    @"Data Source=(LocalDB)\MSSQLLocalDB;
    AttachDbFilename=""C:\Users\scara\Documents\nea2022 database.mdf"";
    Integrated Security=True;
    Connect Timeout=30");

Sign up to request clarification or add additional context in comments.

Comments

1

Use second double quotes to escape them inside the verbatim string:

SqlConnection Con = new SqlConnection(
    @"Data Source=(LocalDB)\MSSQLLocalDB;
    AttachDbFilename=""C:\Users\scara\Documents\nea2022 database.mdf"";
    Integrated Security=True;
    Connect Timeout=30");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.