2011-11-04 237 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() 
}