Multiple SQL queries asp.net c#

后端 未结 5 1901
忘掉有多难
忘掉有多难 2020-12-31 18:08

I need to run several queries inside one function, will I have to create a new SqlConnection for each? Or having one connection but different SqlCommands works too?

5条回答
  •  心在旅途
    2020-12-31 18:58

    Purely as an alternative to the using statements:

    SqlConnection con = new SqlConnection(myConnectionString);
    
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandText = @"SELECT [stuff] FROM [tableOfStuff]";
    
    con.Open();
    
    SqlDataReader dr = null;
    try
    {
        dr = cmd.ExecuteReader();
    
        while(dr.Read())
        {
            // Populate your business objects/data tables/whatever
        }
    }
    catch(SomeTypeOfException ex){ /* handle exception */ }
    
    // Manually call Dispose()...
    if(con != null) con.Dispose();
    if(cmd != null) cmd.Dispose();
    if(dr != null) dr.Dispose();
    

    The major difference between this and the using statements, is this will allow you to handle exceptions more cleanly.

提交回复
热议问题