Making sense of database responses

We're nearing the end of a large system for the lovely people over at Consolidated Communications Management Ltd and we've just come across a nice idea to make sense of database responses. Typically in the past we've simply returned -1/0 for failure and a positive integer (usually an id) of it was successful. The new method should add a little more conformity to our code. We already use a common Database Access Layer which handles the opening/closing of our connection, adding parameters etc but I’ve just added an enum with the common database responses, thought it may be of use to others:

public enum DatabaseResponse{...}{    Success = 0,    Init = -1,    Found = -2,    NotFound = -3,    Duplicate = -4}

This should cover the common responses from our database however to make it a little more futureproof we'll keep -1 through to -10 reserved for this data level and then start more specific responses from -11 (i.e. BadPassword).

Using it is simple (this is not real code before you ask!):

public bool Save(){...}{    DatabaseLayer DBLayer = new DatabaseLayer();//Check whether we should be saving or inserting this recordif (this.Id == (int)DatabaseLayer.DatabaseResponse.Init){...}    {//The Id's set to initialised only so insert//The create method simply inserts the values into the database and returns//either the Id of the newly inserted record or our database responsethis.Id = DBLayer.Create(this);if (this.Id >= (int)DatabaseLayer.DatabaseResponse.Success){...}        {//The insert was a successreturn true;         }else{...}        {//The insert failed for some reason -you could throw an error//to catch or simply bubble the response upto to the code behind layerreturn false;         }    }else{...}    {//When updating the record don't use the Id to store the response, instead//throw it into a temp object and use that so the Id's still stored in the objectint response = DBLayer.Update(this);if (response == (int)DatabaseLayer.DatabaseResponse.Success)return true; //All's okelsereturn false; //Something went wrong -it could be the item wasn't found etc    }}

Subscribe to TSD

Don’t miss out on the latest posts. Sign up now to get access to the library of members-only posts.
jamie@example.com
Subscribe