-2

I have a field that's stored in the database as a string. It's actually a comma-separated string of numbers that I convert to a list of longs. The lines of code that do the conversion look somewhat like this:

TheListOfLongs = (from string s in StringFromDB.Split(',') 
                  select Convert.ToInt64(s)).ToList<long>();

The code that creates the database storage string looks like this:

return String.Join(",", TheListOfLongs.Select(x=> x.ToString()).ToArray());

This works fine but as you can see, if for some reason there's a problem with the string, the code in the first line of code breaks on Convert.ToInt64(s).

Now I know I can wrap all this around a try statement but my question is this: can storing and retrieving a string in the database corrupt the string (in which case I definitely need the try statement) or is this a one a trillion odd type of event?

frenchie
  • 46,331
  • 96
  • 283
  • 483
  • 1
    What does the record look like that "breaks on `Convert.ToInt64(s)`"? – Yuck Feb 12 '13 at 19:07
  • @Yuck: well it doesn't break (for now). It's a string of number separated by commas: 28983,3553,57523,5334,35543,4636343,16941,4223,53534.... – frenchie Feb 12 '13 at 19:09
  • 2
    No, a database isn't arbitrarily going to "corrupt data" behind your back. Yes, illegal data can get into a database unless you rigorously validate it before "insert" or "update". [GIGO](http://en.wikipedia.org/wiki/Garbage_in,_garbage_out). And yes, unless you're absolutely sure that *nothing* will *ever* go wrong (famous last words!), you should definitely code the correct error handling in the appropriate place. IMHO... – paulsm4 Feb 12 '13 at 19:13
  • Why the downvote? Care to explain? – frenchie Feb 12 '13 at 19:19

2 Answers2

1

Selecting from the DB shouldn't corrupt your string.

If the connection is dropped mid transfer or something like that then an exception is thrown.

Andrew Walters
  • 4,592
  • 6
  • 31
  • 47
1

I wouldn't worry about corrupt data per se. However, you definitely need to handle the more general case where you can't parse what should be numeric data.

Even in the most controlled situations it is good programming practice to provide conditions for when you can't process data as you're expecting to be able to. What that means to your application is something you'll need to decide. Wrapping the statement with a try..catch will prevent your application from choking, but may not be appropriate if the parsed list is critical later on.

Yuck
  • 44,893
  • 13
  • 100
  • 132