开发者

Make connection to database only once on page load

开发者 https://www.devze.com 2023-01-19 13:31 出处:网络
When I load my page I populate 开发者_运维问答my repeater with the following code. Dim conn As Data.SqlClient.SqlConnection

When I load my page I populate 开发者_运维问答my repeater with the following code.

        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

Now I want to call another Stored Procedure (at the same time) so that I can populate some text fields (also on Page Load). But how can I do this so that I only make a call to my database once for better performance?

C# examples will also work if you don't know VB.NET


Just don't close the connection and fire off another stored procedure. Close the connection afterwards. So you would Dim another SQL command and execute it.

Something like:

Dim Comm2 As Data.SqlClient.SqlCommand
Dim reader2 as Data.SqlClient.SqlDataReader

Comm2.CommandType = CommandType.StoredProcedure
Comm2.Paramaters.AddWithValue("@whateverValue", "Whatever")

then just after you open the connection

reader2 = Comm2.ExecuteReader()

Then you'll find reader2 has what you want, but you used the same connection for both.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号