我建议您在 SQL Server 上创建一个存储过程,这是一个示例:
CREATE PROCEDURE sp_UpdateEmployeeByID
(
@ID int,
@TitleID int,
@FirstName nvarchar(255),
@LastName nvarchar(255)
)
AS
BEGIN
SET NOCOUNT ON;
UPDATE Employee SET
TitleID = @TitleID,
FirstName = @FirstName,
LastName = @LastName
WHERE ID = @ID
END
使用存储过程而不是 ad-hoc SQL 可以保护您免受 SQL 注入攻击,而且还有性能优势。
然后使用 VB.Net,您将需要调用存储过程,传入更新的员工值。
Public Sub UpdateEmployeeByID(Byval ID As Int32, Byval TitleID As Int32, Byval FirstName As string, Byval LastName As string)
Dim connString As String = ConfigurationManager.AppSettings("ConnectionString")
Dim conn As New SqlConnection(connString)
conn.Open()
Dim sqlCommand As new SqlClient.SqlCommand("sp_UpdateEmployeeByID", conn)
sqlCommand.CommandType = CommandType.StoredProcedure
sqlCommand.Parameters.AddWithValue("@ID", ID)
sqlCommand.Parameters.AddWithValue("@TitleID", TitleID)
sqlCommand.Parameters.AddWithValue("@FirstName", FirstName)
sqlCommand.Parameters.AddWithValue("@LastName", LastName)
Try
sqlCommand.ExecuteNonQuery()
Catch ex As SqlException
'Handle SQL exceptions
Catch ex As Exception
'Handle exceptions
Finally
'clean up resources that access Data
If IsNothing(sqlCommand) = False Then
sqlCommand.Dispose()
sqlCommand = Nothing
End If
conn.Close()
End Try
End Sub