2016-08-09 139 views
0

當我運行鱈魚我看到這些錯誤 SelectCommand屬性尚未初始化調用'填充'之前。 的 「adb.Fill(DS1)」vb.net SelectCommand屬性尚未初始化之前調用'填充'

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

_Dim adb As New SqlClient.SqlDataAdapter(「select * from」&tablename&「order by&orderbyfield)_但請注意您的輸入。這是一個開放的sql注入(和缺少的空間) – Steve

+0

你只把選擇命令放在一個字符串中,你必須以某種方式將它提交給'SqlDataAdapter'(構造函數,.SelectCommand屬性等) –

回答

0

嘗試......

首先,你必須使用參數化查詢,以避免SQL注入。

所有你需要的是,A SQLCommand有一個有效的sql查詢的對象。然後,您應該將該SQLCommand對象作爲參數傳遞給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 
+0

不工作顯示在c1上的文本框1我想當我點擊Button1顯示c3和當點擊agen顯示c4 ....等 –

相關問題