Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically convert .Net null to DBNull.Value?

I've written a utility to handle adding values to data parameters for hand-rolling sql queries. Consumption looks like

utility.Add("SELECT * FROM MyTable WHERE MyColumn = {0}", myVariable, DBType.TheType);

or

utility.Add("UPDATE MyTable SET MyColumn = {0}", myVariable, DBType.TheType);

How should a null value for myVariable be handled?

  1. All values should be fully trusted. The responsibility is solely upon the consumer. How would the consumer know that null would be handled anyway?
  2. null can never work, so it should throw a NullArgumentException. Why go any further?
  3. null should be automatically interpreted as DBNull.Value since it's the only viable solution. This is a utility, right? Make it utilizable and dry up some code!

Optional bonus question: If these arguments were made by three political candidates, what would their parties be? (Please state the home country of such parties)

like image 423
StarTrekRedneck Avatar asked Nov 14 '22 18:11

StarTrekRedneck


1 Answers

Rock the Null Coalescing Op:

In your add put another parm for the =... utility.Add("SELECT * FROM MyTable WHERE MyColumn {0}{1}", myVariable, DBType.TheType);

When you format the string in the Add method: ... = String.Format(sql,myVariable is null ? " IS " : " = ", myVariable ?? "Null"

You'll probably want to expound on that a bit, e.g., stick with on parameter and toss in a temp stringbuilder; might have to use a the ?/: construct for the type, too, wherever that's being used. Good luck.

like image 180
FastAl Avatar answered Nov 24 '22 01:11

FastAl