If VbConn.State = ConnectionState.Closed Then
VbConn.ConnectionString = VbConnectionString
VbConn.Open()
Dim VbCommand As System.Data.SqlClient.SqlCommand = VbConn.CreateCommand
VbCommand.CommandText="SELECT * FROM Test WHERE test1=@p1"
VbCommand.Parameters.AddWithValue("@p1" , "a123")
Dim ExecuteReturn As Integer = VbCommand.ExecuteNonQuery
VbCommand.Cancel()
VbConn.Close()
End If
接著說明DataAdapter如何使用參數
Dim MyDataTable As New DataTable
Dim GetData As String=""
Using VbConn As SqlClient.SqlConnection = New SqlClient.SqlConnection(VbConnectionString)
Using Adp As New System.Data.SqlClient.SqlDataAdapter("SELECT * FROM Test WHERE test1=@p1", VbConn)
Adp.SelectCommand.Parameters.AddWithValue("@p1" , "A123")
Adp.Fill(MyDataTable)
End Using
End Using
For i = 0 To MyDataTable.Rows.Count - 1 Step 1
GetData = MyDataTable.Rows(i).Item("欄位名稱")
Next
使用參數化查詢並沒有特別困難,但是要特別注意!!
以SELECT * FROM Test WHERE test1=@p1 這個範例來說,無論test1這個欄位是不是文字格式,都只要輸入test1=@p1就好,千萬不要輸入test1='@p1',會造成系統錯誤。
補充:
如果使用的是OdbcParameter 參數的使用會比較不同
範例:
If VbConn.State = ConnectionState.Closed Then
VbConn.ConnectionString = VbConnectionString
VbConn.Open()
Dim VbCommand As System.Data.Odbc.OdbcCommand = VbConn.CreateCommand
VbCommand.CommandText="SELECT * FROM Test WHERE test1=? AND test2=?"
VbCommand.Parameters.Add("test1" ,OdbcType.VarChar).Value="A1234"
VbCommand.Parameters.Add("test2" ,OdbcType.Int).Value="1234"
Dim ExecuteReturn As Integer = VbCommand.ExecuteNonQuery
VbCommand.Cancel()
VbConn.Close()
End If
詳細說明請參考:https://msdn.microsoft.com/zh-tw/library/zxdcah9t(v=vs.110).aspx
沒有留言:
張貼留言