Home > Blockchain >  sql server database connection not working in c#
sql server database connection not working in c#

Time:05-09

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

CodePudding user response:

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

CodePudding user response:

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