繁体   English   中英

asp.net数据库连接

[英]asp.net database connection

我的asp.net项目中的web.config文件中有正确的条目。 如何确保成功建立连接? 我想从数据库中提取图像,然后将其显示在我的aspx页面上。 注意事项:我使用的是Visual Studio 2010,SQL Server 2008,.NET 4.0

谢谢

这是我的web.config文件中的相关部分

<databases >

<add key="MyConnection" name="MyName" value="server=servername\\SQL2008;uid=myuid;pwd=mypwd;database=databaseName;"/ >

    `<add key="DataAccessClass" value="DataAccessSql"/`>  
`</databases`>  

我的项目中还没有任何app.config文件。 令人惊讶的是,我的web.config中没有该节。 我需要明确添加一个吗?

Web.config文件只是用于配置设置的存储。 为了建立与数据库的连接,您需要编写一些代码。

ASP.NET-数据库连接

创建与SQL Server的连接

在web.config文件中输入的连接参数仅仅是参数。 没有实际的连接。 实际上,可以在web.config中创建多个连接参数,并且可以在运行时进行实际连接。

要真正建立连接,您需要定义

例如,此处将SQLDataSource设置为连接到ConnectionStrings.MyNorthwind

<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 LastName FROM Employees">
      </asp:SqlDataSource>

      <asp:ListBox
          id="ListBox1"
          runat="server"
          DataTextField="LastName"
          DataSourceID="SqlDataSource1">
      </asp:ListBox>

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

或在第二个示例中,他们显式创建一个SqlConnection。 这里的连接字符串将从web.config中获取。

private static void ReadOrderData(string connectionString)
{
    string queryString = 
        "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

这是在web.config中找到的连接字符串的示例

<configuration>
  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM