Wednesday, November 22, 2017

Fill DataTable from sql query string (c# , SQL)


In c#, we can directly query the database from a query string using SqlConnection. We need to open a connection to the database, pass our query using SqlCommand, fetch and load the result in a DataTable and finally close the connection.

Below is a sample function for this operation. Further, you can modify it to meet your need.

Use the following namespace:

using System.Data;
 using System.Data.SqlClient; 

The connection string and query string can be modified or passed as the arguments in the function.

private DataTable GetFromDatabase()
{
DataTable returnTable = new DataTable();
using (SqlConnection con = new SqlConnection("Your_ConnectionString"))
{
con.Open();
using (SqlCommand command = new SqlCommand("Your_sql_query_string", con))
using (SqlDataReader reader = command.ExecuteReader()) { returnTable.Load(reader); }
con.Close();
}
return returnTable;
}

No comments:

Post a Comment