0

我在 vb.net 中有一个程序,我需要将数据插入到数据库中。当我运行此代码时,出现错误:

没有为命令对象设置命令文本

这是我的代码:

Private Sub InsertRelease(strRelease As String, rowInserted As Boolean)
    On Error GoTo errH

    Dim con As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim strPath As String
    Dim intImportRow As Integer
    Dim objType As String
    Dim strUsername, strPassword, strTable, strDatabase, strDsn, strSystem, strNewSql, sqlStr As String
    Dim intRecsAffected As Integer
    Dim boolRowInserted As Boolean

    strDsn = ComboBox1.Text
    strSystem = txtSystem.Text
    strUsername = txtUser.Text
    strPassword = txtPassword.Text

    If con.State <> 1 And strUsername <> "" And strPassword <> "" Then
         con.Open("{iSeries As ODBC Driver};System=" + strSystem + ";Dsn=" + strDsn + "; Uid=" + strUsername + "; Pwd=" + strPassword + ";")
    Else
        MessageBox.Show("Please enter the correct UserName And Password")
        txtUser.Focus()
        con = Nothing
    End If
    sqlStr = "insert into jobscopedb.ppusrfs (search_key_uf,DATA_ITEM_UF, NUMERIC_VALUE_UF) values (strRelease,'81 AB',0);"
    strNewSql = ""

    con.Execute(strNewSql, intRecsAffected)
    con.Close()
    con = Nothing
    boolRowInserted = (intRecsAffected > 0)
    If (boolRowInserted) Then
        MessageBox.Show("Release " + strRelease + " added")
    Else
        MessageBox.Show("Release " + strRelease + "not added")
    End If
    Exit Sub
errH:
    MsgBox(Err.Description)
    con = Nothing

End Sub
4

1 回答 1

0

下面演示了您的代码在使用 ADO.net 时的样子。

将连接字符串直接传递给连接的构造函数,并将命令文本和连接传递给命令的构造函数。打开连接并执行命令。ExecuteNonQuery返回受影响的行。

始终使用参数来避免 sql 注入。

Private Sub InsertRelease(strRelease As String)
    Dim intRecsAffected As Integer
    Dim strDsn = ComboBox1.Text
    Dim strSystem = txtSystem.Text
    Dim strUsername = txtUser.Text
    Dim strPassword = txtPassword.Text
    'Validate Input
    If strUsername = "" OrElse strPassword = "" Then
        MessageBox.Show("Please enter the correct UserName And Password")
        txtUser.Focus()
        Exit Sub
    End If

    Using con As New OdbcConnection($"{{iSeries As ODBC Driver}};System={strSystem};Dsn={strDsn}; Uid={strUsername}; Pwd={strPassword};"),
            cmd As New OdbcCommand("insert into jobscopedb.ppusrfs (search_key_uf, DATA_ITEM_UF, NUMERIC_VALUE_UF) values (@Release,'81 AB',0);", con)
        cmd.Parameters.Add("@Release", OdbcType.VarChar).Value = strRelease
        con.Open()
        intRecsAffected = cmd.ExecuteNonQuery
    End Using 'Closes and disposes the connection and command even it there is an error

    If intRecsAffected = 1 Then
        MessageBox.Show("Release " + strRelease + " added")
    Else
        MessageBox.Show("Release " + strRelease + "not added")
    End If
End Sub
于 2020-12-10T07:33:00.257 回答