0

我正在寻找很多在线连接到 MS SQL 数据库的方法。我在 web.config 中使用连接字符串。它对我们想要的效果非常好,看起来像这样:

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

这是最好的连接方式。然后我将它与一个主要使用gridview的asp web表单应用程序一起使用

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

            SelectCommand="SELECT * FROM [xxx].[Matcxxxh]"
            UpdateCommand="UPDATE [xxx].[Matxxxch] SET [xxx] = 
              @xxx, [xxx] = @xxx, [xxx] = 
              @xxx WHERE x=@xxxAnd x=@xxx"
            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. 脚本完成运行后如何在最后关闭连接?
4

2 回答 2

2
  1. 这是从配置中使用连接字符串的众多方法之一。没有什么问题。看起来不错。

  2. 不,因为这是一个主观的事情,而不是我们在这里回答的那种事情。

  3. 脚本完成后连接将关闭。你不需要做任何事情(SqlDataSource照顾所有的细节)。

于 2012-05-04T10:57:16.790 回答
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();
    }

这种方式在您的应用程序中提供了更多的重用,并使更改更容易。

于 2012-05-04T13:43:36.123 回答