connectionstring configured in app.config how to use in main program console app I'm using .net 6.0
app.config
program.cs
string connect = ConfigurationManager.ConnectionStrings["Server"].ConnectionString;
connect.Open();
SqlCommand command = new SqlCommand();
DataSet dataSet = new DataSet();
command.CommandText = "SpData";
command.CommandType = CommandType.StoredProcedure;
SqlDataAdapter Adapter = new SqlDataAdapter(command.CommandText, connect);
Adapter.Fill(dataSet, "SpData");
DataTable t1 = dataSet.Tables["SpData"];
foreach (DataColumn column in t1.Columns)
{
value += column.ColumnName + '^';
}
value += "\r\n";
if (t1 != null & t1.Rows.Count > 0)
{
foreach (DataRow row in t1.Rows)
{
foreach (DataColumn column in t1.Columns)
{
string cellValue = row[column.ColumnName].ToString() + '^';
value += cellValue;
}
value += "\r\n";
}
Tuhin PaulPosted Mar 24, 2023, 2:59 AM
You can check this improved version:
By default, SqlConnection objects are pooled by the .NET Framework. This means that after the SqlConnection is closed, it is not immediately terminated but instead returned to the connection pool for reuse. You can set the connection string property "Pooling" to false if you want to disable connection pooling. Alos you can use the using statement for the SqlCommand and SqlDataAdapter objects to ensure that they are properly disposed of when they are no longer needed.
Tuhin PaulPosted Mar 23, 2023, 6:31 PM
Based on the accepted answer, I am tring to add some improvements for example
1. Use a try-catch block to handle exceptions that may occur while executing the code.
2. Add parameterized queries instead of using a plain text command, which can prevent SQL injection attacks.
Naimish MakwanaPosted Mar 23, 2023, 3:09 PM
You can use like below:
Thanks
Jignesh KumarPosted Mar 23, 2023, 10:49 AM
Hello Meghana,
It looks correct to me. Are you facing any issue for above code ?