假设我有一个 MySql 存储过程,它插入一条带有一些可为空 CHAR 字段的记录。
在 VB.NET 中,如果我不检查 Nothing(或其他语言中的 Null),我会从数据库驱动程序中得到异常,因此我写道:
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("_name", if(name Is Nothing, "", name)).Direction = ParameterDirection.Input;
这是我不喜欢的第一件事;我想传递 Nothing 并且驱动程序知道它必须将 NULL 放入数据库中。但是,在存储过程中,我必须检查该字段是否为空:
INSERT INTO mytable
(
name,
-- other 200 char fields
)
VALUES
(
NULLIF(_name, ''),
-- other 200 char fields
)
丑陋呃?我必须检查两次是否为虚无/空虚。
有没有更好、更直接的方法呢?
更糟糕的是,对于非引用类型(即:整数),检查是否为空是没有意义的,因为原始类型不可能是空的(是的,我可以将整数设置为无意义的值,例如 -1 表示正 id , 但...)。
Let's say I have a MySql stored procedure that inserts a record with some nullable CHAR fields.
In VB.NET if I don't check for Nothing (or Null in other languages), I get an exception from the db driver, so I write:
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("_name", if(name Is Nothing, "", name)).Direction = ParameterDirection.Input;
And this is the first thing I don't like; I'd like to pass Nothing and the driver knows it has to put NULL in the Db. But then, in the stored procedure, I have to check back the field if it is empty:
INSERT INTO mytable
(
name,
-- other 200 char fields
)
VALUES
(
NULLIF(_name, ''),
-- other 200 char fields
)
Ugly uh? I have to check for nothingness/emptiness twice.
Is there a better, more direct, way?
Even worse, for non reference types (i.e: Integers) the check for nothingness makes no sense, since a primitive type can't be nothing (yes, I could set an Integer to a non meaningful value, say -1 for a positive id, but...).
发布评论
评论(3)
如果要插入
NULL
,请使用 next:相同
与查看 MSDN
如果你想插入空字符
''
你接下来:Use next if you want to insert
NULL
:means the same as
See more about null-coalescing operator on MSDN
And if you want to insert empty char
''
you next:DbNull.Value 并不能解决问题,如果不指定参数可为空,则会抛出异常。
这样就可以了。我不必检查 SP 中的空字符串(或奇怪的“不可能”值)。
当然,您可以编写一个共享通用方法来简化参数设置,适用于任何数据库/语言类型:
并像这样调用它:
DbNull.Value doesn't solve the problem, the exception is thrown if you don't specify that the parameter is nullable.
This way it works. I don't have to check for the empty string (or weird "impossible" value) in the SP.
Of course you can write a shared generic method to easy the parameter setting, working for any database/language type:
And call it like:
使用
DbNull.Value
而不是空字符串。Use
DbNull.Value
instead of the empty string.