将参数传递给 SQL 服务器从多个不同事件插入查询

Pass parameters to SQL Server insert query from multiple different events

我正在 Visual Studio 2013 年编写一个 Winforms 应用程序,它有多种形式。我正在添加一个事件日志来查看谁在使用什么,登录时间,注销时间等(都是无害的,这是工作团队的管理工具)。我想简化和减少所需的代码长度。

现在我在所有表单的每个事件子中都有以下代码。

 Dim connection As New SqlConnection("Server= server\instance; Database = db;
                                      User ID=uID;Password=pw")

 Private Sub btnAssociate_Click(sender As Object, e As EventArgs) Handles btnAssociate.Click
    Dim eLogCMD As New SqlCommand("sp_EventLog", connection)
    Me.connection.Open()
    eLogCMD.CommandType = CommandType.StoredProcedure
    eLogCMD.Parameters.AddWithValue("@Username", Login.UsernameTextBox.Text.ToString())
    eLogCMD.Parameters.AddWithValue("@Action", "AssociateArea")
    eLogCMD.Parameters.AddWithValue("@Comments", "Entered Associate Area")
    eLogCMD.ExecuteNonQuery()
    Me.connection.Close()

还有其他几个Sub,都是相同的代码,多个表单,相同的连接,SqlCommand,声明的参数;只有参数值改变。它有效,但必须有一种更清洁的方法。

我想在主窗体上创建一个 SqlConnectionSqlCommand 以从不同的窗体和事件子窗体调用和传递参数。我正在寻找像这样简单的东西:

Sub --Whatever Event
    Main.eLogCMD.ExecuteNonQuery(1stParameterValue, 2ndParameterValue, 3rdParameterValue)
End Sub

显示 SQL 服务器存储过程:

CREATE PROCEDURE [dbo].[sp_EventLog]        
     @Username VARCHAR(50),
     @Action   VARCHAR(30),
     @Comments VARCHAR(100)     
AS       
BEGIN
    INSERT INTO AppEventLog ([Username], [Action], [Comments])
    VALUES (@Username, @Action, @Comments)      
END

请勿将此部分制作成任何形式。相反,您可以将代码放在它自己的模块中。然后使用编写日志所需的参数调用模块上的方法。

不要尝试在您的应用程序中重复使用相同的连接 object。这将干扰 ADO.Net 中称为连接池的功能。您可以(并且应该)重复使用相同的连接字符串,但这是不同的。

Public Module Events 
    Private CnString As String = "Server= server\instance; Database = db; User ID=uID;Password=pw"

    Public Sub LogAction(User As String, ActionName As String, Comment As String)
        Using cn As New SqlConnection(CnString), _
              LogCmd As New SqlCommand("sp_EventLog", cn)

            LogCmd.CommandType = CommandType.StoredProcedure
            'AVOID ADDWITHVALUE()! It can cause significant performance problems
            'Instead, set these to match actual column types and lengths from the DB
            LogCmd.Parameters.Add("@Username", SqlDbType.NVarChar, 30).Value = User
            LogCmd.Parameters.Add("@Action", SqlDbType.NVarChar, 80).Value = ActionName
            LogCmd.Parameters.Add("@Comments", SqlDbType.NVarChar, 500).Value = Comment

            cn.Open()
            LogCMD.ExecuteNonQuery()
        End Using
    End Sub  
End Module

然后您现有的方法减少到使用此模式:

Private Sub btnAssociate_Click(sender As Object, e As EventArgs) Handles btnAssociate.Click
    Events.LogAction(Login.UsernameTextBox.Text, "AssociateArea", "Entered Associate Area")

    '...
End Sub

理想情况下,ALL 数据库访问将 运行 通过像这样的模块,其中用户界面事件永远不会直接与数据库对话,而只会调用数据库上的方法模块。