连接ASP.. NET网站到SQL数据库

本文关键字:SQL 数据库 网站 ASP NET 连接 | 更新日期: 2023-09-27 18:13:30

我目前正在尝试建立一个ASP。. NET网站项目和SQL Server 2008 R2构建的数据库。

我需要这样做的方式是使用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>

连接ASP.. NET网站到SQL数据库

使用配置管理器:

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);
}

关于在ASP中使用SQL身份验证连接到SQL Server的文章。. NET可能会让你更好地了解需要做什么。

作为预检查,只需检查您的mssqlserver服务是否正在运行

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()
}