473,387 Members | 1,535 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

SqlCommand Best Practices

233 100+
I am tryign to figure out what the best practice for exception handling is in regards to SqlCommand. I am mostly concerned with data exceptions when the command is executed. Here is what I have started on:

Expand|Select|Wrap|Line Numbers
  1.  
  2. private void CreateOpportunity(string PODoc)
  3. {
  4. string Conn = "Data Source=server11;Initial Catalog=Main;User ID=uid;Password=pw";
  5. string Account = "Name";
  6. OpportunityID = NewID("opportunity");
  7. AccountID = "A6UJ9A002N65";
  8. using (SqlConnection slxConn = new SqlConnection(Conn))
  9. {
  10. string sql = "INSERT INTO sysdba.OPPORTUNITY (OPPORTUNITYID,ACCOUNTID,DESCRIPTION,CLOSED,STATUS,SECCODEID,CREATEUSER,CREATEDATE,MODIFYUSER,MODIFYDATE) VALUES (@opportunityid,@accountid,@description,@closed,@status,@seccodeid,@createuser,@createdate,@modifyuser,@modifydate)";
  11. SqlCommand cmd = new SqlCommand(sql, slxConn);
  12. cmd.Parameters.AddWithValue("@opportunityid", OpportunityID);
  13. cmd.Parameters.AddWithValue("@accountid", AccountID);
  14. cmd.Parameters.AddWithValue("@description", PONum);
  15. cmd.Parameters.AddWithValue("@closed", "F");
  16. cmd.Parameters.AddWithValue("@status", "In-Process");
  17. cmd.Parameters.AddWithValue("@seccodeid", "SYST00000001");
  18. cmd.Parameters.AddWithValue("@createuser", "Admin");
  19. cmd.Parameters.AddWithValue("@createdate", DateTime.Now);
  20. cmd.Parameters.AddWithValue("@modifyuser", "Admin");
  21. cmd.Parameters.AddWithValue("@modifydate", DateTime.Now);
  22. try
  23. {
  24. slxConn.Open();
  25. cmd.ExecuteNonQuery();
  26. }
  27. catch (SqlException ex)
  28. {
  29. string str;
  30. str = "Source:" + ex.Source;
  31. str += "\n" + "Message:" + ex.Message;
  32. }
  33. finally
  34. {
  35. if (slxConn.State == ConnectionState.Open)
  36. {
  37. slxConn.Close();
  38. }
  39. //method to send error message
  40. //SendError(str);
  41. }
  42. }
  43.  
Jan 8 '09 #1
3 4672
balabaster
797 Expert 512MB
As a rule, exceptions are a relatively expensive operation so where they can be handled ahead of time, you should. Put as little as you can get away with inside a try {} catch {}.

Consequently you should predict any potential data errors creating your parameters and avoid having to handle exceptions. Usually the only exceptions you'll get are data type or null - so a simple check to make sure that the data is there and the right format will perform a lot better than handling exceptions on them.

When creating commands, the only thing I put in the try {} catch {} is the execution. If I throw an exception outside that, then it should be caught by my unit tests. There should be no excuse for invalid data to make it as far as parameter creation, in either direction (from the db -> GUI or from GUI -> db)
Jan 8 '09 #2
mcfly1204
233 100+
So it would make more sense to check the length of the parameters, and their content prior to executing the command? Though I was not aware of the expense of exceptions, it now makes sense. Thanks for the prompt reply as always.
Jan 8 '09 #3
balabaster
797 Expert 512MB
I usually check the value as I'm assigning it to my parameters to make sure that no exception will occur. If all of my parameters are created successfully then my command will have the correct amount of parameters which I check prior to execution of my command.

And in fact, if all your parameters haven't been created properly you can avoid having to even open the database connection.
Jan 8 '09 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: byrocat | last post by:
I'm chasing after a documetn that was available on one of the Microsoft websites that was titled somethign like "MS SQL Server Best Practices" and detailed a nyumber of best practices about...
136
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their...
10
by: Henrik Dahl | last post by:
Hello! After I've finished using an instance of the SqlCommand class, should I then invoke Dispose() on the instance. I suppose so, as there is a Dispose method, but what does it actually...
13
by: john doe | last post by:
A quick question, about so-called 'best practices', I'm interested in which of A/B of the two examples people would choose, and why. public enum MyEnum { Option1 = 0, Option2 = 1, Option3 =...
2
by: Amelyan | last post by:
Could anyone recommend a book (or a web site) that defines best practices in ASP.NET application development? E.g. 1) Precede your control id's with type of control btnSubmit, txtName, etc. 2)...
10
by: jojobar | last post by:
Hello, I am trying to use vs.net 2005 to migrate a project originally in vs.net 2003. I started with creation of a "web site", and then created folders for each component of the site. I read...
10
by: Ren | last post by:
Hi All, I'm still rather new at vb.net and would like to know the proper way to access private varibables in a class. Do I access the variable directly or do I use the public property? ...
3
by: John Dalberg | last post by:
I am looking for an ASP.NET application on CodePlex which exemplifies best practices for the following: - Use of interfaces - Seperation of the UI, business and data tiers - Data Tier that uses...
6
by: Frank Hauptlorenz | last post by:
Hello, I'm trying to send an SqlCommand to a WCF-Service. For this I'm using the following DataContract: public class SqlCommandComposite { SqlCommand cmd = new SqlCommand();
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.