2011-11-04 238 views
3

我正在嘗試建立ASP.NET網站項目和SQL Server 2008 R2構建的數據庫之間的連接。將ASP.NET WebSite連接到SQL數據庫

我需要這樣做的方式是使用Web.config頁面中的connectionString,但我不知道給它提供什麼值或如何使用所述值建立連接。 (使用C#)

任何幫助將不勝感激,因爲我發現旁邊沒有關於這個問題的信息。

這裏是(默認)值,是目前在Web.config頁:

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

這可能是對你有用...它創建連接字符串一招http://stackoverflow.com/questions/3954029/how-to-use-sqlconnect-or-sqldriverconnect/3954073#3954073 –

+2

「我發現旁邊沒有關於這個主題的信息」 - 單獨在SO上有超過5000次點擊「連接字符串」! – Jason

+0

@酸,你得到它的工作? – KreepN

回答

5

使用Configuration Manager:

using System.Data.SqlClient; 
using System.Configuration; 

string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString; 

using(SqlConnection SqlConnection = new SqlConnection(connectionString)); 

//剩下的就是在這裏向您展示這方面會怎樣使用。但是,這個評論上面的代碼是你真正要求的,這是如何連接。

{ 

    SqlDataAdapter SqlDataAdapter = new SqlDataAdapter(); 
    SqlCommand SqlCommand = new SqlCommand(); 

    SqlConnection.Open(); 
    SqlCommand.CommandText = "select * from table"; 
    SqlCommand.Connection = SqlConnection; 
    SqlDataReader dr = SqlCommand.ExecuteReader(CommandBehavior.CloseConnection); 

} 
+0

如果在執行讀寫器之前發生異常,連接將不會關閉。因此我建議使用'use'塊。 – abatishchev

+0

個人喜好,因爲他可以在try-catch塊中使用它。不過,我同意,並會確保我相應地記錄下來。 – KreepN

+0

這確實告訴我如何檢索連接字符串,以便爲我回答部分問題。在「Web.config」文件中寫什麼是另一回事。目前,我只是簡單地做了這個:'Server = localhost; Trusted_Connection = yes; Database = mydb',它可以工作,但它與默認值相差太遠了。 – Acidic

0
string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; 

using (SqlConnection connection = new SqlConnection(connectionString)) 
using (SqlCommand command = connection.CreateCommand()) 
{ 
    command.CommandText = commandText; 

    // command.Parameters.AddWithValue("@param", value); 

    connection.Open(); 
    command.ExecuteNonQuery(); // or command.ExecuteScalar() or command.ExecuteRader() 
}