vb.net在调用'Fill'之前尚未初始化SelectCommand属性

时间:2016-08-09 12:41:41

标签: sql-server vb.net

当我运行鳕鱼时,我看到了这些错误 在调用“填充”之前,尚未初始化SelectCommand属性。 在“adb.Fill(ds1)”

Imports System.Data.Sql
Module ComModule
Public sqlconn As New SqlClient.SqlConnection
Public Sub openconn()
    If sqlconn.State = 1 Then sqlconn.Close()
    Try
        sqlconn.ConnectionString = "Data Source=MRSOFTWARE-PC;Initial Catalog=ComShop;Integrated Security=True"
        sqlconn.Open()
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Not Connection", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign)
        sqlconn.Close()
        End
    End Try
End Sub
Public Function LastNum(tablename, orderbyfield) As Integer
    LastNum = 0
    Dim str = "select * from " & tablename & "order by" & orderbyfield
    Dim adb As New SqlClient.SqlDataAdapter()
    Dim ds1 = New DataSet
    adb.Fill(ds1)
    Dim DT As DataTable
    DT = ds1.Tables(0)
    If DT.Rows.Count <> 0 Then
        Dim i = DT.Rows.Count - 1
        LastNum = Val(DT.Rows(i).Item(0))
    End If
End Function

结束模块

TextBox1.Text = Format(LastNum("Customer", "CustomerId") + 1, "c0")

1 个答案:

答案 0 :(得分:0)

试试这个......

首先,您必须使用参数化查询来避免SQL注入。

您需要的只是一个具有有效sql查询的SQLCommand对象。然后,您应该将该SQLCommand对象作为args传递给SQLAdapter构造函数。

Imports System.Data.Sql
    Module ComModule
        Public sqlconn As New SqlClient.SqlConnection
        Public Sub openconn()
            If sqlconn.State = 1 Then sqlconn.Close()
            Try
                sqlconn.ConnectionString = "Data Source=MRSOFTWARE-PC;Initial Catalog=ComShop;Integrated Security=True"
                sqlconn.Open()
            Catch ex As Exception
                MessageBox.Show(ex.Message, "Not Connection", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign)
                sqlconn.Close()
                End
            End Try
        End Sub
        Public Function LastNum(tablename, orderbyfield) As Integer
            LastNum = 0
            Dim str = "select * from @tablename order by @orderbyfield"
            Dim sqlCmd As New SqlClient.SqlCommand(str , sqlCon)
            sqlCmd.Parameters.Add("@tablename", SqlDbType.VarChar, 50).Value=tablename
            sqlCmd.Parameters.Add("@orderbyfield", SqlDbType.VarChar, 50).Value=orderbyfield
            Dim adb As New SqlClient.SqlDataAdapter(sqlCmd)
            Dim ds1 = New DataSet
            adb.Fill(ds1)
            Dim DT As DataTable
            DT = ds1.Tables(0)
            If DT.Rows.Count <> 0 Then
                Dim i = DT.Rows.Count - 1
                LastNum = Val(DT.Rows(i).Item(0))
            End If
        End Function


    End Module