1

I am trying to connect to a SQL Server database in my website. I have created a database from Add -> Add New Item -> SQL Server database. The name of my database file is database.mdf.

I have created a ConnectionString:

<connectionStrings>
    <add name="Khulna_website"
         connectionString= "Server=(localDB)\\v11.0;Integrated Security=SSPI;Database=Database.mdf;"
         providerName="System.Data.SqlClient" />
</connectionStrings>

My first question is, when I open a database that way, is it necessary to add a connection string? Asking that because I can already see a green connection line on the side of the database.

Then, how do I connect it on my C# code?

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();

The question is, what do I add on ["RegistrationConnectionString"] part? Should I give the name of my ConnectionString? Am I missing any point here? I am completely new here. Any help would be highly appreciated.

2 Answers 2

1

Yes, in order to connect to a database - you do need some form of a connection string - one way or another. It's typically considered a best practice to put those connection strings into a config file, so you can modify it without changing your code.

To retrieve the actual connection string from the config, you need to use the name=.... to you gave it in the config file:

<add name="Khulna_website"
           ***************  this is the **name** of your connection string

Retrieve it like this:

string conStr = ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString;
                                                        ************** same name again

and then use it to create your connection object to the database:

SqlConnection conn = new SqlConnection(conStr);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help!
0

Put the name of the connection string which is Khulna_website instead of RegistrationConnectionString

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.