JigJagJoe
JigJagJoe

Reputation: 45

Connecting to SQL Server database in ASP.NET

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.

Upvotes: 1

Views: 2031

Answers (2)

marc_s
marc_s

Reputation: 754220

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

Upvotes: 1

Black Panther
Black Panther

Reputation: 145

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

Upvotes: 0

Related Questions