VB.Net将字符串解析为日期

时间:2018-08-24 12:16:12

标签: sql vb.net

我看过但找不到解决我问题的方法。我正在使用以下代码从CSV文件导入数据:

Using connection As New SqlClient.SqlConnection(SqlconnectionString)
    Dim cmd As New SqlClient.SqlCommand(strsql, connection)
    With cmd.Parameters
        .Add("@PLAASNOMMER", SqlDbType.VarChar, 50, "F1")
        .Add("@PLAASNAAM", SqlDbType.VarChar, 50, "F2")
        .Add("@BLOKNOMMER", SqlDbType.VarChar, 50, "F3")
        .Add("@AREA", SqlDbType.VarChar, 50, "F4")
        .Add("@KULT", SqlDbType.VarChar, 50, "F7")
        .Add("@WINGERDKLAS", SqlDbType.VarChar, 50, "F8")

        .Add("@ANALISEDATUM", SqlDbType.Date).Value = Date.ParseExact("F9", "dd/MM/yyyy", DBNull.Value)

        .Add("@SUIKERWAARDE", SqlDbType.Decimal, 50, "F10")
        .Add("@PHWAARDE", SqlDbType.Decimal, 50, "F11")
        .Add("@SUURWAARDE", SqlDbType.Decimal, 50, "F12")
    End With

    Dim adapter As New SqlClient.SqlDataAdapter()
    adapter.InsertCommand = cmd
    Dim iRowsInserted As Int32 = adapter.Update(dt)

我在CSV文件中将“空”日期显示为“ / /”。我正在使用代码(第10行):

.Add("@ANALISEDATUM", SqlDbType.Date).Value = Date.ParseExact("F9", "dd/MM/yyyy", DBNull.Value)

但是我遇到错误

  

无法将类型为“ System.DBNull”的对象转换为类型为“ System.IFormatProvider”。

我想念什么?

我的CSV日期如下:

plaasno,name1,blokno,name2,analise_dt,name3,kult,wingklas,datum,suiker,ph,suur,deurryppnt,geur
"11332","MONOTONKA","1-MON","KLEINPLASIE","20090115","","PIN","KULT","  /  /",0.00,0.00,0.00,0.00,0.00
"11332","MONOTONKA","10-MON","KLEINPLASIE","20090115","","COL","BULK","  /  /",0.00,0.00,0.00,0.00,0.00
"11332","MONOTONKA","10-MON","VREDENDAL","20180228","","COL","BULK","28/02/18",23.50,3.08,10.42,0.00,0.00
"11332","MONOTONKA","12-MON","KLEINPLASIE","20090115","","CHB","BULK","  /  /",0.00,0.00,0.00,0.00,0.00
"11332","MONOTONKA","12-MON","VREDENDAL","20180214","","CHB","BULK","14/02/18",18.70,3.09,11.78,0.00,0.00
"11332","MONOTONKA","13-MON","KLEINPLASIE","20090115","","CHB","BULK","  /  /",0.00,0.00,0.00,0.00,0.00
"11332","MONOTONKA","13-MON","VREDENDAL","20180214","","CHB","BULK","14/02/18",18.30,3.03,13.28,0.00,0.00

2 个答案:

答案 0 :(得分:1)

错误本身是很容易解释的,您正在将System.DBNull传递给一个参数,该参数希望在此处为Date.ParseExact-method传递iFormatProvider:

Date.ParseExact("F9", "dd/MM/yyyy", DBNull.Value)

不确定是否要尝试执行此操作,如果无法解析该值,也许想传递null?在这种情况下,您可以使用TryParseExact进行if子句,并且如果返回false,则将DBNull.Value添加为参数的值。

正如@AndrewMorton所指出的那样,您正在将文字字符串“ F9”(以及所有其他字段也)传递给函数,而不是csv中的值。您的代码不完整。无论如何,根据您的问题,我已经解释了为什么会出现您描述的错误。

答案 1 :(得分:0)

.TryParseExact还有更多参数。 如果必须将.Add输入两次,因为我无法将DBNull.Value分配给Date变量。

    Dim d As Date
    Dim F9 As String = "String that must match your format parameter"
    'Your command and parameter code
    If Date.TryParseExact(F9, "yyyy-mm-dd", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, d) Then
        .Add("@ANALISEDATUM", SqlDbType.Date).Value = d
    Else
        .Add("@ANALISEDATUM", SqlDbType.Date).Value = DBNull.Value
    End If