【问题标题】:Make connection to database only once on page load在页面加载时只连接一次数据库
【发布时间】:2010-10-12 17:10:06
【问题描述】:

当我加载我的页面时,我使用以下代码填充我的转发器。

        Dim conn As Data.SqlClient.SqlConnection
        Dim Comm As Data.SqlClient.SqlCommand
        Dim reader As Data.SqlClient.SqlDataReader

        'conn = New Data.SqlClient.SqlConnection("Server=localhost\sqlexpress; " & _
        '"Database=MyDB; Integrated Security=true")
        conn = New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("MyConnection").ConnectionString)

        Comm = New Data.SqlClient.SqlCommand( _
        ("HomePage"), conn)

        Comm.CommandType = CommandType.StoredProcedure
        Comm.Parameters.AddWithValue("@currentState", "Florida")

        ' Open the connection
        conn.Open()
        ' Execute the category command
        reader = Comm.ExecuteReader()

        ' Bind the reader to the repeater.......
        blogRepeater.DataSource = reader

        blogRepeater.DataBind()

        ' Close the reader
        reader.Close()
        ' Close the connection
        conn.Close()

    End Try

现在我想(同时)调用另一个存储过程,以便我可以填充一些文本字段(也在页面加载上)。但是我该如何做到这一点,以便我只调用一次我的数据库以获得更好的性能?

如果您不了解 VB.NET,也可以使用 C# 示例

【问题讨论】:

    标签: c# asp.net sql-server vb.net database-connection


    【解决方案1】:

    只是不要关闭连接并启动另一个存储过程。之后关闭连接。因此,您将 Dim 另一个 SQL 命令并执行它。

    类似:

    Dim Comm2 As Data.SqlClient.SqlCommand
    Dim reader2 as Data.SqlClient.SqlDataReader
    
    Comm2.CommandType = CommandType.StoredProcedure
    Comm2.Paramaters.AddWithValue("@whateverValue", "Whatever")
    

    然后在你打开连接之后

    reader2 = Comm2.ExecuteReader()
    

    然后你会发现 reader2 有你想要的,但你对两者使用了相同的连接。

    【讨论】:

    • 在性能与代码可维护性竞赛中,这是最好的选择
    • 谢谢大佬,其实很简单!谢谢!
    • @Etienne - 没问题,很高兴我能帮上忙
    猜你喜欢
    • 2012-01-18
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多