Automatically convert .Net null to DBNull.Value?

I wrote a utility to handle adding values ​​to data parameters for manual 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 the null value for myVariable be handled?

  • All values ​​must be fully trusted. Responsibility lies solely with the consumer. How does the consumer know that null will be processed anyway?
  • null can never work, so it should throw a NullArgumentException. Why move on?
  • null should be automatically interpreted as DBNull.Value, as this is the only viable solution. This is a utility, right? Make it recyclable and dry the code!

Bonus Bonus Additional Question: If these arguments were made by three political candidates, what would their sides be? (Please indicate the country of origin of such parties)

+5
source share
2 answers

Scan Null Coalescing Op :

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

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

, , , , temp stringbuilder; , ? /: , . .

+1

Null - , DBNull, .

0

All Articles