yana
yana

Reputation: 11

sql server database connection not working in c#

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 ://

Upvotes: 0

Views: 795

Answers (2)

Guru Stron
Guru Stron

Reputation: 143083

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

Upvotes: 1

Shahaf Machluf
Shahaf Machluf

Reputation: 63

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

Upvotes: 2

Related Questions