在双变量中保留 NULL 值 [英] Preserving NULL values in a Double Variable

查看:22
本文介绍了在双变量中保留 NULL 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个从 Excel 电子表格导入的 vb.net 应用程序.

I'm working on a vb.net application which imports from an Excel spreadsheet.

If rdr.HasRows Then
        Do While rdr.Read()
            If rdr.GetValue(0).Equals(System.DBNull.Value) Then
                Return Nothing
            Else
                Return rdr.GetValue(0)
            End If
        Loop
    Else

我使用字符串值来存储双精度值,在准备数据库语句时我会使用以下代码:

I was using string value to store the double values and when preparing the database statement I'd use this code:

If (LastDayAverage = Nothing) Then
            command.Parameters.AddWithValue("@WF_LAST_DAY_TAG", System.DBNull.Value)
        Else
            command.Parameters.AddWithValue("@WF_LAST_DAY_TAG", Convert.ToDecimal(LastDayAverage))
        End If

我现在有一些小数位相当多的数据,并且数据以科学计数法放入字符串变量中,所以这似乎是错误的方法.开始使用字符串变量似乎不太正确.

I now have some data with quite a few decimal places and the data was put into the string variable in scientific notation, so this seems to be the wrong approach. It didn't seem right using the string variable to begin with.

如果我使用双精度或十进制类型变量,空白 Excel 值会显示为 0.0.

If I use a double or decimal type variable, the blank excel values come across as 0.0.

如何保留空白值?

注意:我已经试过了

变量为 Nullabe(Of Double)

Variable as Nullabe(Of Double)

但是当将值传递给 SQL 插入时,我得到:可空对象必须有一个值."

But when passing the value to the SQL insert I get: "Nullable object must have a value."

解决方案:

通过更改我正在调用的子程序中参数的数据类型,然后使用 Variable.HasValue 进行条件 DBNull 插入来修复.

Fixed by changing the datatype of the parameter in the sub I was calling and then using Variable.HasValue to do the conditional DBNull insert.

推荐答案

我不知道您使用哪个 API 进行数据库插入,但是对于其中许多 API,包括 ADO.NET,插入空值的正确方法是使用 DBNull.Value.所以我的建议是您在 VB 代码中使用 Nullable(Of Double),但是当需要进行插入时,您可以将任何空值替换为 DBNull.Value.

I don't know which API you're using to do database inserts, but with many of them, including ADO.NET, the proper way to insert nulls is to use DBNull.Value. So my recommendation is that you use Nullable(Of Double) in your VB code, but then when it comes time to do the insert, you'd substitute any null values with DBNull.Value.

这篇关于在双变量中保留 NULL 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆