.NET 和 MySql 参数,AddWithValue NULL 变量,如何避免检查空值

发布于 2024-09-19 09:33:36 字数 672 浏览 6 评论 0 原文

假设我有一个 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...).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

囍孤女 2024-09-26 09:33:36

如果要插入 NULL,请使用 next:

command.Parameters.AddWithValue("_name", name ?? DBNull.Value);

相同

if(name != null)
    command.Parameters.AddWithValue("_name", name);
else
    command.Parameters.AddWithValue("_name", DBNull.Value);

与查看 MSDN

如果你想插入空字符 '' 你接下来:

command.Parameters.AddWithValue("_name", name ?? '');

Use next if you want to insert NULL:

command.Parameters.AddWithValue("_name", name ?? DBNull.Value);

means the same as

if(name != null)
    command.Parameters.AddWithValue("_name", name);
else
    command.Parameters.AddWithValue("_name", DBNull.Value);

See more about null-coalescing operator on MSDN

And if you want to insert empty char '' you next:

command.Parameters.AddWithValue("_name", name ?? '');
℉絮湮 2024-09-26 09:33:36

DbNull.Value 并不能解决问题,如果不指定参数可为空,则会抛出异常。

Dim par As New MySqlParameter("p1", Nothing)
par.IsNullable = True
par.MySqlDbType = MySqlDbType.Int32 ' or any other type you need '
par.Direction = ParameterDirection.Input
command.Parameters.Add(par)
command.ExecuteNonQuery()

这样就可以了。我不必检查 SP 中的空字符串(或奇怪的“不可能”值)。

当然,您可以编写一个共享通用方法来简化参数设置,适用于任何数据库/语言类型:

Public Shared Function GetNullableSqlParameter(Of T As IComparable)(ByVal parameterName As String, ByVal parameterType As MySqlDbType, ByVal value As T, Optional ByVal nonNullable As T = Nothing) As MySqlParameter

        Dim par As New MySqlParameter
        par.ParameterName = parameterName
        par.MySqlDbType = parameterType
        par.Direction = ParameterDirection.Input

        If value Is Nothing OrElse (nonNullable IsNot Nothing AndAlso nonNullable.Equals(value)) Then
            par.IsNullable = True
            par.Value = DBNull.Value
            par.SourceColumnNullMapping = True
        Else
            par.IsNullable = False
            par.Value = value
        End If

        Return par
    End Function

并像这样调用它:

command.Parameters.Add(General.GetNullableSqlParameter("_zip", MySqlDbType.String, zipcode))

DbNull.Value doesn't solve the problem, the exception is thrown if you don't specify that the parameter is nullable.

Dim par As New MySqlParameter("p1", Nothing)
par.IsNullable = True
par.MySqlDbType = MySqlDbType.Int32 ' or any other type you need '
par.Direction = ParameterDirection.Input
command.Parameters.Add(par)
command.ExecuteNonQuery()

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:

Public Shared Function GetNullableSqlParameter(Of T As IComparable)(ByVal parameterName As String, ByVal parameterType As MySqlDbType, ByVal value As T, Optional ByVal nonNullable As T = Nothing) As MySqlParameter

        Dim par As New MySqlParameter
        par.ParameterName = parameterName
        par.MySqlDbType = parameterType
        par.Direction = ParameterDirection.Input

        If value Is Nothing OrElse (nonNullable IsNot Nothing AndAlso nonNullable.Equals(value)) Then
            par.IsNullable = True
            par.Value = DBNull.Value
            par.SourceColumnNullMapping = True
        Else
            par.IsNullable = False
            par.Value = value
        End If

        Return par
    End Function

And call it like:

command.Parameters.Add(General.GetNullableSqlParameter("_zip", MySqlDbType.String, zipcode))
︶ ̄淡然 2024-09-26 09:33:36

使用 DbNull.Value 而不是空字符串。

Use DbNull.Value instead of the empty string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文