尝试通过 mySQL 数据库将数据输入到我的 .NET 程序中

问题描述

您好,我正在尝试将数据库中的数据导入到程序中的变量中,但一直出现错误

system.invalidCastException: '从'dbnull' 类型到'String' 类型的转换无效。'


       Dim value As Integer
       Dim MysqLConn As MysqLConnection
       Dim sql As New MysqLCommand

       Dim dataAdapter As New MysqLDataAdapter
       Dim dataFromDB As New DataSet
       Dim numrows As Integer

       MysqLConn = New MysqLConnection
       MysqLConn.ConnectionString = "server=localhost;user id=root;database=gamedata;"

       Try
           MysqLConn.open()

           sql = New MysqLCommand("SELECT Ccost FROM cards WHERE `UserName` = '" & UserName & "' AND `Game` = '" & game & "'",MysqLConn)

           dataAdapter = New MysqLDataAdapter(sql)
           dataAdapter.Fill(dataFromDB)
           numrows = dataFromDB.Tables(0).Rows.Count

           For counter = 1 To numrows - 1
               value = dataFromDB.Tables(0).Rows(counter).Item(0)
           Next

           sql = New MysqLCommand("Select Level,Health,score,PlayerTime FROM savedata WHERE `UserName` = '" & UserName & "' AND `Game` = '" & game & "'",MysqLConn)

           dataAdapter = New MysqLDataAdapter(sql)
           dataAdapter.Fill(dataFromDB)
           numrows = dataFromDB.Tables(0).Rows.Count
           
           'For counter = 0 To 1
           level = dataFromDB.Tables(0).Rows(0).Item(0)
           Phealth = dataFromDB.Tables(0).Rows(0).Item(1)
           score = dataFromDB.Tables(0).Rows(0).Item(2)
           time = dataFromDB.Tables(0).Rows(0).Item(3)

          

       Catch ex As MysqLException
           MsgBox("Error " & ex.Message)
       End Try

数据库代码

use `Gamedata`;

create table `SaveData`
(`GameCode` int AUTO_INCREMENT not null,`Game` enum('1','2','3','4') not null,`UserName` varchar(20) not null,`level` int not null,`Health` int not null,`score` int not null,`PlayerTime` time not null,foreign key(`UserName`) REFERENCES `player` (`UserName`),primary key(`GameCode`));

解决方法

这是一种稍微不同的方法。此代码需要文件顶部的以下导入。

Imports System.Data.SqlTypes

您需要使用 Using 块声明您的数据库对象,以便即使出现错误它们也会被关闭和处理。应始终使用参数编写查询。不仅避免了sql注入,而且更易于读写。

数据库整数可以为空,但在 .net 中则不然。 SqlInt32 有一个 .IsNull 属性,可用于测试。如果您尝试通过调用 .ToString 等方式将空字符串转换为字符串,则会出现错误。

Private ConStr As String = "server=localhost;user id=root;database=gamedata;"

Private Sub OpCode(UserName As String,Game As String)
    Dim value As Integer

    Dim dt As New DataTable

    Dim strSql = "SELECT Ccost FROM cards WHERE `UserName` = @UserName AND `Game` = @Game"
    Try
        Using Sql As New MySqlCommand(strSql,New MySqlConnection(ConStr))
            Sql.Connection.Open()
            Sql.Parameters.Add("@UserName",MySqlDbType.VarChar).Value = UserName
            Sql.Parameters.Add("@Game",MySqlDbType.VarChar).Value = Game
            Dim obj = Sql.ExecuteScalar
            value = If(obj Is Nothing,CInt(obj))
            Sql.CommandText = "Select Level,Health,Score,PlayerTime FROM savedata WHERE `UserName` = @UserName AND `Game` = @Game;"
            Using reader = Sql.ExecuteReader
                dt.Load(reader)
            End Using
        End Using
        Dim level = If(CType(dt.Rows(0)(0),SqlString).IsNull,"",dt.Rows(0)(0).ToString)
        Dim Phealth = If(CType(dt.Rows(0)(1),dt.Rows(0)(1).ToString)
        Dim score = If(CType(dt.Rows(0)(2),SqlInt32).IsNull,CInt(dt.Rows(0)(2)))
        Dim time = If(CType(dt.Rows(0)(3),CInt(dt.Rows(0)(3)))
    Catch ex As MySqlException
        MsgBox("Error " & ex.Message)
    End Try
End Sub