C# - SPLessons

Read connection string from web.config

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Read connection string from web.config

Read connection string from web.config

Description:

Hi Every one, today we are going to learning how to read connection string from web.config file.

Step 1: Here we have connection string in web config file.

[csharp]

// Web.config

<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="publichealthConnectionString" connectionString="Data Source=SPLESSONS\SQLEXPRESS;Initial Catalog=publichealth;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

</configuration>

[/csharp]

Step 2: Add System.Configuration reference to your program.

Step 3: Use the connection like bellow :

[csharp]

String customconnectionString = ConfigurationManager.ConnectionStrings["publichealthConnectionString"].ConnectionString;

try
{
string sql = "insert into patient(name) values (@name)";
using (SqlConnection conn = new SqlConnection(customconnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@name", firstname); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}

[/csharp]

 

Comments