How to read created connection string of Web.Config in C# code behind to pass query? [Resolved]

Posted by Nikhilst05 under C# on 10/6/2011 | Points: 10 | Views : 29994 | Status : [Member] | Replies : 3
I want to know that How to read created connection string of Web.Config in code behind to pass query?

My project is C# ASP.NET 4.0 and Sql Server 2010 based.

for e.g. if my Connection String in Web.Config

<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>


than, how to use it in Code behind to pass some sql query say,
select *  nikhil where name='Tamhankar';





Responses

Posted by: Ndebata on: 10/6/2011 [Member] Starter | Points: 50

Up
0
Down

Resolved
First add a reference to System.Configuration

string conString = System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;

DataTable dt = new DataTable();
using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(conString))
{
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = @"select * from nikhil[TABLENAME] where name=@Name";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", "Tamhankar");
con.Open();

using (SqlDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
}
}
}
// Now you can use this datatable dt


Nikhilst05, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Blessyjees on: 10/6/2011 [Member] Bronze | Points: 25

Up
0
Down
Hi,

You can use system.Data.Sql namespace and its classes

See this link http://www.techtoolblog.com/archives/webconfig-connection-string-settings-in-net-20

Blessy Baby
Digitalmesh Softech pvt Ltd
https://blessybaby.wordpress.com/

Nikhilst05, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Atshul on: 7/2/2013 [Member] Starter | Points: 25

Up
0
Down
Dear All,

please tell me my web config file where i am establish connection with our database so please tell me it is correct or not or there is any changes required because i am facing several problems like as..dataset is empty or connection did not open or close properly. connection is connected. or table 0 can not found or table column <field1> not found....if i will restart IIS then every think is Ok then these problems will not occur until 1 hr or may be 4 hr.

<connectionStrings>
<add name="SQLConnectStr" connectionString="Data Source=server\sqlexpress;Initial Catalog=DOCDATA;User ID=sa;Password=sa;"/> </connectionStrings>





Atul Sharma

Nikhilst05, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response