SqlDataSource.ConnectionString SqlDataSource.ConnectionString SqlDataSource.ConnectionString SqlDataSource.ConnectionString Property

定义

获取或设置特定于 ADO.NET 提供程序的连接字符串,SqlDataSource 控件使用该字符串连接基础数据库。Gets or sets the ADO.NET provider-specific connection string that the SqlDataSource control uses to connect to an underlying database.

public:
 virtual property System::String ^ ConnectionString { System::String ^ get(); void set(System::String ^ value); };
public virtual string ConnectionString { get; set; }
member this.ConnectionString : string with get, set
Public Overridable Property ConnectionString As String

属性值

.NET Framework 的SqlDataSource特定于数据访问接口的字符串, 用于连接到它所表示的 SQL 数据库。A .NET Framework data provider-specific string that the SqlDataSource uses to connect to the SQL database that it represents. 默认值为空字符串("")。The default is an empty string ("").

示例

本部分包含两个代码示例。This section contains two code examples. 第一个代码示例演示如何将ConnectionString属性设置为连接到 Microsoft SQL Server 数据库, 并在GridView控件中显示SelectCommand属性的结果。The first code example demonstrates how to set the ConnectionString property to connect to a Microsoft SQL Server database and display the results of the SelectCommand property in a GridView control. 第二个代码示例演示了更复杂的方案, SqlDataSource其中控件用于显示和更新受密码保护的 Microsoft Access 数据库中的数据。The second code example demonstrates a more complex scenario, where a SqlDataSource control is used to display and update data in a password-protected Microsoft Access database. 在每种情况下connectionStrings , 首先显示 web.config 文件的元素, 后跟SqlDataSource包含控件的 ASP.NET 页。In each case, the connectionStrings element of the Web.config file is shown first, followed by the ASP.NET page that contains the SqlDataSource control.

下面的代码示例演示如何将ConnectionString属性设置为连接到 SQL Server 数据库, 并在GridView控件中显示SelectCommand属性的结果。The following code example demonstrates how to set the ConnectionString property to connect to a SQL Server database and display the results of the SelectCommand property in a GridView control.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <asp:SqlDataSource
          id="SqlDataSource1"
          runat="server"
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT FirstName, LastName, Title FROM Employees">
      </asp:SqlDataSource>

      <asp:GridView
          id="GridView1"
          runat="server"
          DataSourceID="SqlDataSource1">
      </asp:GridView>

    </form>
  </body>
</html>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <asp:SqlDataSource
          id="SqlDataSource1"
          runat="server"
          DataSourceMode="DataReader"
          ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
          SelectCommand="SELECT FirstName, LastName, Title FROM Employees">
      </asp:SqlDataSource>

      <asp:GridView
          id="GridView1"
          runat="server"
          DataSourceID="SqlDataSource1">
      </asp:GridView>

    </form>
  </body>
</html>

下面的代码示例演示了一个比前面的代码示例更复杂的方案, SqlDataSource其中, 控件用于显示和更新受密码保护的访问数据库中的数据。The following code example demonstrates a more complex scenario than the preceding code example, where a SqlDataSource control is used to display and update data in a password-protected Access database. 由于与 Access 一起使用ProviderName , 因此System.Data.OleDb属性设置为提供程序, 并且ConnectionString属性设置为 UNC 共享访问数据库的相应连接字符串。 SqlDataSourceBecause the SqlDataSource is used with Access, the ProviderName property is set to the System.Data.OleDb provider, and the ConnectionString property is set to an appropriate connection string for a UNC-shared Access database. GridView控件显示具有装运日期的订单。A GridView control displays orders with shipment dates. 您可以通过选中相应的复选框, 然后单击 "更新" 按钮来更新订单。You can update an order by checking the appropriate check box, and then clicking the Update button.

重要

此示例包含纯文本格式的密码, 仅用于说明目的。This example includes a password in plain text only for illustration purposes. 在生产应用程序中, 应对包含密码的连接字符串进行加密。In a production application, connection strings that include passwords should be encrypted. 有关详细信息,请参阅保护连接信息For more information, see Protecting Connection Information.

<%@Page  Language="C#" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
private void UpdateRecords(Object source, EventArgs e)
{
  // This method is an example of batch updating using a
  // data source control. The method iterates through the rows
  // of the GridView, extracts each CheckBox from the row and, if
  // the CheckBox is checked, updates data by calling the Update
  // method of the data source control, adding required parameters
  // to the UpdateParameters collection.
  CheckBox cb;
  foreach(GridViewRow row in this.GridView1.Rows) {
    cb = (CheckBox) row.Cells[0].Controls[1];
    if(cb.Checked) {
      string oid = (string) row.Cells[1].Text;
      MyAccessDataSource.UpdateParameters.Add(new Parameter("date",TypeCode.DateTime,DateTime.Now.ToString()));
      MyAccessDataSource.UpdateParameters.Add(new Parameter("orderid",TypeCode.String,oid));
      MyAccessDataSource.Update();
      MyAccessDataSource.UpdateParameters.Clear();
    }
  }
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

<!-- Security Note: The SqlDataSource uses a QueryStringParameter,
     Security Note: which does not perform validation of input from the client.
     Security Note: To validate the value of the QueryStringParameter, handle the Selecting event. -->

      <asp:SqlDataSource
        id="MyAccessDataSource"
        runat="server"
        ProviderName="<%$ ConnectionStrings:MyPasswordProtectedAccess.providerName%>"
        ConnectionString="<%$ ConnectionStrings:MyPasswordProtectedAccess%>"
        SelectCommand="SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE EmployeeID=?"
        UpdateCommand="UPDATE Orders SET ShippedDate=? WHERE OrderID = ?">
        <SelectParameters>
          <asp:QueryStringParameter Name="empId" QueryStringField="empId" />
        </SelectParameters>
      </asp:SqlDataSource>

      <asp:GridView
        id ="GridView1"
        runat="server"
        DataSourceID="MyAccessDataSource"
        AllowPaging="True"
        PageSize="10"
        AutoGenerateColumns="False">
          <columns>
            <asp:TemplateField HeaderText="">
              <ItemTemplate>
                <asp:CheckBox runat="server" />
              </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Order" DataField="OrderID" />
            <asp:BoundField HeaderText="Order Date" DataField="OrderDate" />
            <asp:BoundField HeaderText="Required Date" DataField="RequiredDate" />
            <asp:BoundField HeaderText="Shipped Date" DataField="ShippedDate" />
          </columns>
      </asp:GridView>

      <asp:Button
        id="Button1"
        runat="server"
        Text="Update the Selected Records As Shipped"
        OnClick="UpdateRecords" />

      <asp:Label id="Label1" runat="server" />

    </form>
  </body>
</html>
<%@Page  Language="VB" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Private Sub UpdateRecords(source As Object, e As EventArgs)

  ' This method is an example of batch updating using a
  ' data source control. The method iterates through the rows
  ' of the GridView, extracts each CheckBox from the row and, if
  ' the CheckBox is checked, updates data by calling the Update
  ' method of the data source control, adding required parameters
  ' to the UpdateParameters collection.

  Dim cb As CheckBox
  Dim row As GridViewRow

  For Each row In GridView1.Rows

    cb = CType(row.Cells(0).Controls(1), CheckBox)
    If cb.Checked Then

      Dim oid As String
      oid = CType(row.Cells(1).Text, String)

      Dim param1 As New Parameter("date", TypeCode.DateTime, DateTime.Now.ToString())
      MyAccessDataSource.UpdateParameters.Add(param1)

      Dim param2 As New Parameter("orderid", TypeCode.String, oid)
      MyAccessDataSource.UpdateParameters.Add(param2)

      MyAccessDataSource.Update()
      MyAccessDataSource.UpdateParameters.Clear()
    End If
  Next
End Sub ' UpdateRecords
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">

<!-- Security Note: The SqlDataSource uses a QueryStringParameter,
     Security Note: which does not perform validation of input from the client.
     Security Note: To validate the value of the QueryStringParameter, handle the Selecting event. -->

      <asp:SqlDataSource
        id="MyAccessDataSource"
        runat="server"
        ProviderName="<%$ ConnectionStrings:MyPasswordProtectedAccess.providerName%>"
        ConnectionString="<%$ ConnectionStrings:MyPasswordProtectedAccess%>"
        SelectCommand="SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE EmployeeID=?"
        UpdateCommand="UPDATE Orders SET ShippedDate=? WHERE OrderID = ?">
        <SelectParameters>
          <asp:QueryStringParameter Name="empId" QueryStringField="empId" />
        </SelectParameters>
      </asp:SqlDataSource>

      <asp:GridView
        id ="GridView1"
        runat="server"
        DataSourceID="MyAccessDataSource"
        AllowPaging="True"
        PageSize="10"
        AutoGenerateColumns="False">
          <columns>
            <asp:TemplateField HeaderText="">
              <ItemTemplate>
                <asp:CheckBox runat="server" />
              </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Order" DataField="OrderID" />
            <asp:BoundField HeaderText="Order Date" DataField="OrderDate" />
            <asp:BoundField HeaderText="Required Date" DataField="RequiredDate" />
            <asp:BoundField HeaderText="Shipped Date" DataField="ShippedDate" />
          </columns>
      </asp:GridView>

      <asp:Button
        id="Button1"
        runat="server"
        Text="Update the Selected Records As Shipped"
        OnClick="UpdateRecords" />

      <asp:Label id="Label1" runat="server" />

    </form>
  </body>
</html>
<script runat="server">
private void UpdateRecords(Object source, EventArgs e)
{
  // This method is an example of batch updating using a
  // data source control. The method iterates through the rows
  // of the GridView, extracts each CheckBox from the row and, if
  // the CheckBox is checked, updates data by calling the Update
  // method of the data source control, adding required parameters
  // to the UpdateParameters collection.
  CheckBox cb;
  foreach(GridViewRow row in this.GridView1.Rows) {
    cb = (CheckBox) row.Cells[0].Controls[1];
    if(cb.Checked) {
      string oid = (string) row.Cells[1].Text;
      MyAccessDataSource.UpdateParameters.Add(new Parameter("date",TypeCode.DateTime,DateTime.Now.ToString()));
      MyAccessDataSource.UpdateParameters.Add(new Parameter("orderid",TypeCode.String,oid));
      MyAccessDataSource.Update();
      MyAccessDataSource.UpdateParameters.Clear();
    }
  }
}
</script>
<script runat="server">
Private Sub UpdateRecords(source As Object, e As EventArgs)

  ' This method is an example of batch updating using a
  ' data source control. The method iterates through the rows
  ' of the GridView, extracts each CheckBox from the row and, if
  ' the CheckBox is checked, updates data by calling the Update
  ' method of the data source control, adding required parameters
  ' to the UpdateParameters collection.

  Dim cb As CheckBox
  Dim row As GridViewRow

  For Each row In GridView1.Rows

    cb = CType(row.Cells(0).Controls(1), CheckBox)
    If cb.Checked Then

      Dim oid As String
      oid = CType(row.Cells(1).Text, String)

      Dim param1 As New Parameter("date", TypeCode.DateTime, DateTime.Now.ToString())
      MyAccessDataSource.UpdateParameters.Add(param1)

      Dim param2 As New Parameter("orderid", TypeCode.String, oid)
      MyAccessDataSource.UpdateParameters.Add(param2)

      MyAccessDataSource.Update()
      MyAccessDataSource.UpdateParameters.Clear()
    End If
  Next
End Sub ' UpdateRecords
</script>

注解

SqlDataSource控件可用于各种 ADO.NET 提供程序, 而用于连接到基础数据源的连接字符串的语法特定于提供程序。The SqlDataSource control can be used with a variety of ADO.NET providers and the syntax of the connection string that is used to connect to an underlying data source is specific to the provider.

配置SqlDataSource控件时, 可以ProviderName将属性设置为数据库类型 (默认值为System.Data.SqlClient), 并将ConnectionString属性设置为包含连接所需信息的连接字符串。到数据库。When you configure a SqlDataSource control, you set the ProviderName property to the type of database (the default is System.Data.SqlClient), and you set the ConnectionString property to a connection string that includes information that is required in order to connect to the database. 连接字符串的内容根据数据源控件所访问的数据库类型而有所不同。The contents of a connection string differ depending on what type of database the data source control is accessing. 例如, 在SqlDataSource连接到 SQL Server 时, 控件需要服务器名称、数据库 (目录) 名称以及有关如何对用户进行身份验证的信息。For example, the SqlDataSource control requires a server name, database (catalog) name, and information about how to authenticate the user when connecting to a SQL Server. 有关连接字符串内容的信息, ConnectionString请参阅类的属性SqlConnection ConnectionString OracleConnection ConnectionString 、类的属性、 OleDbConnection类的属性或ConnectionStringOdbcConnection类的属性。For information about the contents of connection strings, see the ConnectionString property for the SqlConnection class, ConnectionString property for the OracleConnection class, ConnectionString property for the OleDbConnection class, or the ConnectionString property for the OdbcConnection class.

如果更改ConnectionString属性DataSourceChanged , 则会引发事件, 从而导致绑定到SqlDataSource控件的任何控件重新绑定。If you change the ConnectionString property, the DataSourceChanged event is raised, causing any controls that are bound to the SqlDataSource control to rebind.

重要

有关存储连接字符串的信息, 请参阅如何:使用数据源控件时保护连接字符串。For information about storing a connection string, see How To: Secure Connection Strings when Using Data Source Controls.

适用于

另请参阅