Simple program without using the open for SqlConnection

  • Thread starter Thread starter Marc Gravell
  • Start date Start date
M

Marc Gravell

As I understand it, if a SqlDataAdapter is given a non-open
connection, it will open it just before it needs it (Fill) and close
it when it has finished (before exiting Fill). If you give it an open
connection it leaves it alone. Note that I'm not really a big
DataAdapter user, so this is just from rough memory...

Marc
 
Hello!

Below is a simple program that works fine.
In this program there is no explicit open for the SqlConnection instead
the DataAdapter will open the Connection to the database automatically.

Now to my question if I check the connection after the SqlDataAdapter has
been created the connection is then closed ?

So when does the SqlDataAdapter open and close the DataAdapter ?

static void Main(string[] args)
{
//Specify SQL Server-specific connection string
SqlConnection thisConnection = new SqlConnection(
@"Server=UHT-DEMO1; Integrated Security=True;" +
"Database=northwind");

//Create DataAdapter object
SqlDataAdapter thisAdapter = new SqlDataAdapter(
"Select CustomerID, ContactName from Customers,
thisConnection);

ConnectionState state1 = thisConnection.State;

//Create DataSet to contain related data tables, rows and
columns
DataSet thisDataSet = new DataSet();

//Fill DataSet using query defined previously for DataAdapter
thisAdapter.Fill(thisDataSet, "Customers");

foreach (DataRow theRow in thisDataSet.Tables["Customers"].Rows)
Console.WriteLine("Row = {0}", theRow["CustomerID"] + "\t" +
theRow["ContactName"]);

Console.WriteLine("Program finished, press Enter/Return to
continue");
Console.Read();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top