gpt4 book ai didi

c# - 将 ASP.NET 网站连接到 SQL 数据库

转载 作者:行者123 更新时间:2023-11-30 15:06:16 25 4
gpt4 key购买 nike

我目前正在尝试在 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>

最佳答案

使用配置管理器:

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

}

关于c# - 将 ASP.NET 网站连接到 SQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8014901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com