我寫了這段代碼來洗掉選定的記錄:
Dim Str As String = "DELETE FROM TableName WHERE ID=" & IDTextBox.Text & ""
Dim cmd As New SqlCommand
If Sqlcon.State = ConnectionState.Open Then Sqlcon.Close()
Sqlcon.Open()
With cmd
.Connection = Sqlcon
.CommandType = CommandType.Text
.CommandText = Str
.ExecuteNonQuery()
.Dispose()
End With
Sqlcon.Close()
但我收到此錯誤:(無法從串列中洗掉當前專案,因為沒有當前專案)
我找不到問題!
uj5u.com熱心網友回復:
您需要驗證文本框中的輸入以確保它是一個數字。(我猜 ID 欄位是一個數字)TryParse將回傳TrueorFalse如果True它用數字填充第二個引數。
將資料庫代碼與用戶界面代碼分開是個好主意。
命令和連接都需要處理,所以它們應該在塊中本地宣告。Using你不應該檢查,ConnectionState因為連接總是在使用它的方法中。無論在何處宣告連接,都將其洗掉。
您可以將CommandText和Connection直接傳遞給 Command 的建構式。CommandType.Text是默認值,因此您沒有明確分配它。
為了避免 sql 注入并確保向服務器提供正確的型別,請始終使用引數。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Id As Integer
If Integer.TryParse(IDTextBox.Text, Id) Then
DeleteRecord(Id)
Else
MessageBox.Show("Please enter a valid ID")
End If
End Sub
Private OPConStr As String = "Your connection string."
Private Sub DeleteRecord(id As Integer)
Dim Str As String = "DELETE FROM TableName WHERE ID= @ID;"
Using SqlCon As New SqlConnection(OPConStr),
cmd As New SqlCommand(Str, SqlCon)
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = id
SqlCon.Open()
cmd.ExecuteNonQuery()
End Using 'disposes the command and closes and disposes the connection
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361779.html
標籤:sql-server 网络
