Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
  public void AddClient(Client obj){
  try{
      using(System.Data.SQLite.SQLiteConnection conn = stock.db.SqlLiteConnection.getSQLLiteConnection()){
      System.Data.SQLite.SQLiteCommand cmd = conn.CreateCommand();
      string sql="insert into Client (email,firstName,lastName,telephone,address,city,state,zip,web) values(@email,@firstName,@lastName,@telephone,@address,@city,@state,@zip,@web)";
      cmd.CommandText = sql;
      cmd.Parameters.AddWithValue("@email", obj.Email);
      cmd.Parameters.AddWithValue("@firstName", obj.FirstName);
      cmd.Parameters.AddWithValue("@lastName", obj.LastName);
      cmd.Parameters.AddWithValue("@telephone", obj.Telephone);
      cmd.Parameters.AddWithValue("@address", obj.Address);
      cmd.Parameters.AddWithValue("@city", obj.City);
      cmd.Parameters.AddWithValue("@state", obj.State);
      cmd.Parameters.AddWithValue("@zip", obj.Zip);
      cmd.Parameters.AddWithValue("@web", obj.Web);
      cmd.ExecuteNonQuery();
      }

  }catch (Exception ex){}

}

I have couple of questions for the above code (1) Do I have to close connection manually? (2) Do i need to dispose Command object? (3) If exception occurs, do i have to close connection and command (4) How to enhance this code further?

share|improve this question
1  
You should add relevant tags to get a better responce –  Philip Mar 4 '12 at 14:36
    
Please explain (4) a bit more... –  Jedidja Mar 4 '12 at 16:16

1 Answer 1

up vote 2 down vote accepted

OK, here goes:
1) No. You're using "using" which means that the object will be disposed of in the end of the block. As part of the Dispose() method, the connection will be closed and its resources released.

2) Not manually, you should open another "using" block to cause the object to Dispose() in the end.

3) Thanks to the using block, when an exception occurs, the object will be disposed because you're thrown out of the block.

4) "Enhance" is vague...

share|improve this answer
    
2) in your first answer says resources will be released inside code block. Why should I open another "using" to dispose command object –  Mark Taylor Mar 4 '12 at 15:47
    
The resources of the object that is handled by the using block... in your case it's the object referenced by conn –  Yochai Timmer Mar 4 '12 at 16:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.