0

我在網上找到很多方法連接到MS SQL數據庫。我在web.config中使用連接字符串。它的工作完全正常,我們想要什麼,看起來像這樣:ASP數據庫連接問題

<connectionStrings> 
    <add name="xxx" 
     connectionString="SERVER=xxx;UID=xxx;Trusted_Connection=Yes;DATABASE=xxx;" 
     providerName="xxx" /> 
</connectionStrings> 

這是最好的方式來連接。我然後用一個asp web表單應用程序大多采用的GridView

<asp:SqlDataSource ID="MatchDataSource" Runat="server" 

      SelectCommand="SELECT * FROM [xxx].[Matcxxxh]" 
      UpdateCommand="UPDATE [xxx].[Matxxxch] SET [xxx] = 
       @xxx, [xxx] = @xxx, [xxx] = 
       @xxx WHERE [email protected] [email protected]" 
      ConnectionString="<%$ ConnectionStrings:xxx %>"> 
      <UpdateParameters> 
       <asp:Parameter Type="String" Name="CSISN"/> 
       <asp:Parameter Type="String" Name="ProcName"/> 

      </UpdateParameters> 
     </asp:SqlDataSource> 

     <asp:GridView ID="GridView1" Runat="server" 
      DataSourceID="MatchDataSource" Width="100%"> 
      <RowStyle BackColor="white" ForeColor="black" Font-Italic="false" BorderColor="Black" /> 


      <Columns> 

       <asp:TemplateField SortExpression="xxx" HeaderText="xxx"> 
        <EditItemTemplate> 
         <asp:TextBox ID="editxxx" Runat="server" Text='<%# Bind("xxx") %>' 
          MaxLength="15" ToolTip="Enter CSI SN"></asp:TextBox> 
         <asp:RequiredFieldValidator ID="RequiredFieldValidator1" Runat="server" ErrorMessage="You must provide a xxx." ControlToValidate="editxxx">*</asp:RequiredFieldValidator> 
        </EditItemTemplate> 
        <ItemTemplate><asp:Label Runat="server" Text='<%# Bind("CSISN") %>' ID="Label1"></asp:Label></ItemTemplate> 
       </asp:TemplateField> 

我的問題,使用它的

  1. 我要對這個正確?
  2. 任何人都可以點我一個適當的教程,將顯示最佳實踐?
  3. 如何在腳本結束運行時關閉連接?

回答

2
  1. 這是很多的方式來使用連接字符串從配置一個。沒有什麼問題。看起來很好。

  2. 不,因爲這是一種主觀的東西,而不是我們在這裏回答的東西。

  3. 當腳本結束時連接將關閉。你不需要做任何事情(SqlDataSource照顧所有的細節)。

0

我會反對使用SqlDataSource。

是的,它在該頁面上運行良好。但是,如果需要使用另一個頁面,則最終需要複製並粘貼它以使其在那裏工作。

我會建議創建某種類的調用數據庫並將其作爲List或IEnumerable返回。然後使用該類,您可以在後面的代碼中分配數據源。

以下是使用實體框架查詢數據的一個小例子。


數據訪問類

public static class DataAccess 
{ 
    public static List<Section> GetDataFromDatabase() 
    { 
     List<Section> recordList; 
     using (CustomEntities context = new CustomEntities()) 
     { 

      IQueryable<Section> query = from records in context.Records 
               select sections; 
      recordList= query.ToList<Record>(); 
     } 
     return recordList; 
    } 
} 

代碼隱藏使用

private void BindLists() 
    { 
     // Get the data 
     List<Section> theData = DataAccess.GetDataFromDatabase(); 

     // Assign the data source 
     gridView.DataSource = theData; 

     // Bind the grid view 
     gridView.DataBind(); 
    } 

這種方式提供了更多的重用整個應用程序,並使得改變容易得多。