Cleaning up an ADO connection.
I have written a class that accesses data from an SQL database. Here is the class:
public DataSet GetData(int nCol)
string cSQLSelect = @"SELECT * FROM table";
SqlConnection conDB = new SqlConnection(GetConnString());
SqlDataAdapter da = new SqlDataAdapter(cSQLSelect, conDB);
DataSet ds = new DataSet();
da.Fill(ds, "table");
return ds;
In my windows form I'm calling this class and binding the first column to a textbox. Here is the code:
private void button1_Click(object sender, EventArgs e)
{
DataSet ds = class.GetData(11007);
textBox1.DataBindings.Add("text", ds, "table.col1");
}
This code works, the data appears in the textbox just as I expected. But here is my concern: Am I leaving the connection open by using this methodology? Apparently the data adapter does not require a call to the open method. So does the connection close automatically?
I'm new to C# programming, and I don't know the best strategy to handle this situation.
Sam HobbsPosted Aug 20, 2010, 6:22 PM
Andrew FensterPosted Aug 20, 2010, 4:53 PM
You can use "using" to clean up your database connection, as in the following code. In Ron's case, however, he doesn't have a database connection to clean up. The DataAdapter is doing it for him. So he doesn't need to do anything more.
Database db = dm.CreateDatabase();
DbTransaction dbTran = null;
using (DbConnection dbConnection = db.CreateConnection())
{
try
{
dbConnection.Open();
dbTran = dbConnection.BeginTransaction();
// Update something here!
dbTran.Commit();
}
catch
{
if (dbTran != null)
try {dbTran.Rollback();} catch {}
throw;
}
}
Sam HobbsPosted Aug 20, 2010, 3:34 PM
Andrew FensterPosted Aug 19, 2010, 7:35 PM