Skip to main content
 首页 » 编程设计

c#之仅在页面加载时连接到数据库一次

2024年02月24日23TianFang

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

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

请您参考如下方法:

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