嘿Guy我需要你的帮助
我正在努力解决如何从vb.net更新数据库sql server中的任何记录
首先。我在vb中创建了一个类来将所有函数和所有函数放在按钮UPDATE事件中,即更有条理。
我已经设法完美地完成了所有编码(更新功能),没有任何错误,但令人惊讶的是,它没有更新任何字段。
请帮助
这是我的课程,我在其中创建所有函数并从按钮均匀调用它们:
Public Function UpdateDataRecord(Command As String) As Integer
Try
SQLConnector.Open()
SQLCommand = New SqlCommand(Command, SQLConnector)
Dim ChangeCount As Integer = SQLCommand.ExecuteNonQuery()
SQLConnector.Close()
Return ChangeCount
Catch ex As Exception
MsgBox(ex.Message)
End Try
Return 0
End Function
这里我的更新按钮
Private Sub updateBtn_Click(sender As Object, e As EventArgs) Handles updateBtn.Click
If IDTextBox.Text <> "" Then
If (NameTextBox.Text.Length) >= 3 Then
Dim UpdateThisNow As String = "Update tblActivity " &
"Set Name='" & NameTextBox.Text & "' " &
"WHERE ID ='" & IDTextBox.Text & "' "
If sqlcontrol.UpdateDataRecord(UpdateThisNow) = 0 Then
MsgBox("Not Found")
Else
MsgBox("Successfully updated")
End If
Else
MsgBox("Data Entered too short!")
End If
Else
MsgBox("You must provide ID number")
End If
End Sub
答案 0 :(得分:0)
尝试用此替换你的功能。
Public Function UpdateDataRecord(ByVal name As String, ByVal id As Integer) As Integer
Dim result As Integer 'will save the affected records count later
Dim sqlConnStr As String = "ConnectionString" 'put a valid connection string value here
Dim sqlCmdStr As String = "UPDATE tblActivity SET Name = @Name WHERE ID = @ID" 'your SQL UPDATE query with parameters to avoid SQL injection attacks
Using sqlConn As New SqlConnection(sqlConnStr) 'declare a SQL connection object and uses your connection string
Using sqlCmd As New SqlCommand(sqlCmdStr) With {.Connection = sqlConn} 'declare a SQL command object and uses your UPDATE query, and the connection object above
Try
sqlConn.Open() 'Open the connection
With sqlCmd.Parameters
.Clear() 'clear the parameters
.AddWithValue("Name", name) 'add the value to the parameterized query using the values you got from your textbox
.AddWithValue("ID", id)
End With
result = sqlCmd.ExecuteNonQuery() 'set the value of the result integer
Catch ex As Exception
result = 0
Finally
sqlConn.Close()
End Try
End Using
End Using
Return result
End Function
然后这样称呼:
sqlcontrol.UpdateDataRecord(NameTextBox.Text, IDTextBox.Text)