2010-10-23 105 views
0

我在我的asp.net項目中的web.config文件中有正確的條目。我如何確保連接已成功建立?我想從我的數據庫中拉出圖像,然後將其顯示在我的aspx頁面上。需要注意以下幾點:我使用Visual Studio 2010,SQL Server 2008中,.NET 4.0asp.net數據庫連接

感謝

下面是相關的部分從我的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中沒有部分。我需要明確添加嗎?

+0

我不明白的問題可以找到一個連接字符串的例子。如果可以連接到數據庫,則連接已建立。你遇到特定問題嗎? – 2010-10-23 21:27:49

+0

不,我只是想知道,簡單地將connectionstring/UID/password/databaseName添加到web.config文件中會在asp.net中打開一個連接?還是我必須明確寫一個C#代碼來建立它? – zack 2010-10-23 21:32:08

回答

1

在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> 
+0

感謝您的詳細解答! – zack 2010-10-23 22:42:22

+0

如果我嘗試在標記中實現連接,我正面臨一個錯誤:我的web.config文件中有:錯誤是這樣的:在應用程序配置中找不到連接名'DescriptionColumn',或連接字符串爲空。 – zack 2010-10-23 23:00:49

+0

應用程序配置文件/它不在我的asp.net項目目錄中。 – zack 2010-10-23 23:03:14