Simple program without using the open for SqlConnection

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tony Johansson

    Simple program without using the open for SqlConnection

    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=north wind");

    //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.Fil l(thisDataSet, "Customers" );

    foreach (DataRow theRow in thisDataSet.Tab les["Customers"].Rows)
    Console.WriteLi ne("Row = {0}", theRow["CustomerID "] + "\t" +
    theRow["ContactNam e"]);

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


  • Marc Gravell

    #2
    Re: Simple program without using the open for SqlConnection

    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

    Comment

    Working...