代码之家  ›  专栏  ›  技术社区  ›  Etienne

在页面加载时仅连接一次数据库

  •  1
  • Etienne  · 技术社区  · 14 年前

    当我加载页面时,我用以下代码填充中继器。

            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示例也可以使用。

    1 回复  |  直到 14 年前
        1
  •  4
  •   m.edmondson    14 年前

    只是不要关闭连接并触发另一个存储过程。然后关闭连接。因此,您将使另一个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有你想要的,但是你对两者都使用了相同的连接。