简体   繁体   English

执行存储过程OnClick

[英]Execute Stored Procedure OnClick

How can I execute a stored procedure on OnClick button with no parameters? 如何在没有参数的OnClick按钮上执行存储过程? I have the following code behind: 我后面有以下代码:

Protected Sub btnExport_Click(sender As Object, e As System.EventArgs) Handles btnExport.Click

        Dim exec As SqlCommand = New SqlCommand("up_ExportFile", conn)
        exec.CommandType = CommandType.StoredProcedure

End Sub

Supposing you have already opened the connection just add the ExecuteNonQuery method 假设您已经打开连接,只需添加ExecuteNonQuery方法

Protected Sub btnExport_Click(sender As Object, e As System.EventArgs) Handles btnExport.Click

        Dim exec As SqlCommand = New SqlCommand("up_ExportFile", conn)
        exec.CommandType = CommandType.StoredProcedure
        exec.ExecuteNonQuery()

End Sub

However I suggest you to not keep a global variable holding your SqlConnection opened for the lifetime of your application. 但是,我建议您不要在应用程序的整个生命周期中保持打开SqlConnection的全局变量。 Remember that the ADO.NET provider for SqlServer implements the connection pooling mechanism and thus, opening a connection is a lightweight procedure. 请记住,SqlServer的ADO.NET提供程序实现了连接池机制 ,因此,打开连接是一个轻量级的过程。
So a better approach is 所以更好的方法是

Using conn = new SqlConnection("your_connection_string_here")
    conn.Open()
    Dim exec As SqlCommand = New SqlCommand("up_ExportFile", conn)
    exec.CommandType = CommandType.StoredProcedure
    exec.ExecuteNonQuery()
End Using

In this way the connection object is created just when needed, and then closed and disposed See Using Statememt 这样,就可以在需要时创建连接对象,然后将其关闭并释放。请参见使用Statememt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM