Close the underlying DataSet explicitly?

I am using a DataSet to retrieve data from Microsoft SQL Server. Do I need to explicitly close the connection (or does the underlying SqlDataAdapter automatically close the connection)?

I always use DataReader (using), but the first time I use DataSet - that’s why it’s interesting to learn about best practice. Thanks in advance.

+5
source share
5 answers

A DataSetis a disabled "view" in the database. That is, you are loading data from the database into DataSet(actually, into DataTablewhich you can put in DataSet), and you can close the connection that you used to fill in DataTableor DataSet.

, . .

, DB-, . .

+3

Dispose() ADO.NET IDisposable: , , , , , ..:

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
    connection.Open();
    using (DataSet ds = new DataSet())
    using (SqlDataAdapter adapter = new SqlDataAdapter(command))
    {
        adapter.Fill(ds);
    }
}
+1

, . - , , DataSet.

0

, , , db.

public DataSet GetData()
{
    SqlDataReader reader;
    string connstr = your conn string;
    SqlConnection conn = new SqlConnection(connstr);
    DataTable st = new DataTable();
    DataSet ds = new DataSet();
    try
    {                   
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Your select query";
        cmd.Connection = conn;
        conn.Open();

        reader = cmd.ExecuteReader();
        dt.Load(reader);
        ds.Tables.Add(dt);
    }
    catch (Exception ex)
    {
        // your exception handling 
    }
    finally
    {
        reader.Close();
        reader.Dispose();
        conn.Close();
        conn.Dispose();
    }    
    return ds;
}
0

, , , .

, datareader, . , , DataAdapter DataSet. , MSSQL, SqlDataAdapter , , , , , SqlCommand.ExecuteScalar ( DataAdapter ) - , SqlCommand .

SqlDataAdapter doc: http://msdn.microsoft.com/en-us/library/zxkb3c3d.aspx

0

All Articles