retrieving data from SQL in VB (part 2)

后端 未结 3 883
难免孤独
难免孤独 2021-01-14 13:24

I am trying to populate a listbox by retrieving data from a database through sql. I have asked this question earlier but i was using a different configuration and the one i\

3条回答
  •  天命终不由人
    2021-01-14 13:51

    The last solution I saw should work, but there are a couple important best practices to keep in mind regarding SQL Server.

    1) Avoid Select * whenever possible, instead name your columns explicitly. Select * causes SQL to perform extra work if you do not intend to pull down all the columns in the table. It's also not future-proof, since a dba could add a VARBINARY(MAX) column in the future, and populate it with gigs worth of blob data, This scenario would make your query as written slow down substantially and unnecessarily.

    2) Always remember to close your SQLConnection when you're done with it. This will free up a SQL connection and resources.

    if (cn.State != ConnectionState.Closed)
    cn.Close();
    

    Another cool trick is to use the USING directive which will dispose of the SqlConnection object when execution passes out of scope.

    using (SqlConnection cn = new SqlConnection(sConnectionString))
    {
        if (cn.State != ConnectionState.Open)
        cn.Open();
    
       // add query code here.
    
        if (cn.State != ConnectionState.Closed)
        cn.Close();
    }
    
    1. don't forget to close your SqlDataReader after the read loop is complete.

      if (!dr.IsClosed) dr.Close();

    I hope this helps.

    Andre Ranieri

提交回复
热议问题