The only problem is that you are not using the using
statement for the SqlConnection
and the DataAdapter
. However, DbDataAdapter.Fill
opens and closes the connection implicitely.
public static DataTable ExecuteQuery(string query, string table)
{
using(SqlConnection cnn = new SqlConnection(ConnectionInfo))
using(SqlDataAdapter Adp = new SqlDataAdapter(query, cnn))
{
DataTable tbl = new DataTable();
Adp.Fill(tbl);
return tbl;
}
}
The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.
Note that
- the
using
statement will close the connection implicitely even on error - i have used
DataAdapter.Fill(DataTable)
because you're using a single table anyway
Edit: i've only just noticed that you are using a parameter for the table-name. You can also use DbDataAdapter.Fill(DataSet, String)
instead. That does not change anything.