我的应用程序输出DBNull,但在数据库中不是DBNull

时间:2019-02-15 16:42:03

标签: mysql vb.net

我的应用程序输出“ System.InvalidCastException:“无法将对象从DBNull强制转换为其他类型。”

Dim sqlquery = String.Format("SELECT id, date, film, start_time, end_time, participants_count, confirmed FROM calendar WHERE id='" & id & "'")
    connection.Open()
    With command
        .Connection = connection
        .CommandText = sqlquery
    End With
    dataadapter.SelectCommand = command
    dataadapter.Fill(datatable)
    id = Convert.ToInt32(datatable.Rows(0).Item("id"))
    Dim date_ As String = datatable.Rows(0).Item("date").ToString
    Dim film As String = datatable.Rows(0).Item("film").ToString
    Dim start_time As String = datatable.Rows(0).Item("start_time").ToString
    Dim end_time As String = datatable.Rows(0).Item("end_time").ToString
    Dim participants_count As Integer = Convert.ToInt32(datatable.Rows(0).Item("participants_count"))
    Dim confirmed As Integer = Convert.ToInt32(datatable.Rows(0).Item("confirmed"))

问题出现在这里:“ participants_count”和“ confirmed”。所有其他列均正常运行。在数据库中,这两列不是DBNull:Picture of the real MySQL-Result。他们甚至不能成为DBNull:MySQL Structure

如果我用MessageBox输出两者的值,则它也不包含任何内容。 如果能成为解决方案,我将不胜感激。

朱利叶斯

2 个答案:

答案 0 :(得分:0)

Dim participants_count As Integer
Integer.TryParse(datatable.Rows(0).Item("participants_count").Tostring, participants_count)

这将尝试将其转换为Integer,如果失败则返回0,否则会将值设置为partners_count。这应该有助于解决DBNull问题。您可以使用“确认”字段来执行此操作。

答案 1 :(得分:0)

无需使用数据表即可获取查询结果。这样一来,您就可以准确了解数据类型,因此发生意外情况的可能性就较小:

lon_0=180

SQL参数应将其Dim connStr = "your connection string" Dim sql = "SELECT `id`, `date`, `film`, `start_time`, `end_time`, `participants_count`, `confirmed` FROM `calendar` WHERE `id` = @id" Dim id = "2" Dim date_ As DateTime Dim start_time As TimeSpan Dim end_time As TimeSpan Dim participants_count As Integer Dim confirmed As Boolean Using conn As New MySqlConnection(connStr) Using cmd As New MySqlCommand(sql, conn) cmd.Parameters.Add(New MySqlParameter With { .ParameterName = "@id", .MySqlDbType = MySqlDbType.VarChar, .Size = 8, .Value = id}) conn.Open() Dim rdr = cmd.ExecuteReader() If rdr.HasRows Then date_ = rdr.GetDateTime(1) start_time = rdr.GetTimeSpan(3) end_time = rdr.GetTimeSpan(4) participants_count = rdr.GetInt16(5) confirmed = rdr.GetBoolean(6) End If conn.Close() End Using End Using .MySqlDbType设置为与数据库中的.Size列匹配。应该选择id函数以匹配数据库中的类型。