首先,在ASP.NET应用程序中添加一个新的“ADO.NET Entity Data Model”,将其连接到SQL Server数据库。然后,通过下面的代码,在ASP.NET Web应用程序中获取数据:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Customers", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Response.Write(reader["CustomerName"].ToString() + "
");
}
}
}
}
}
在上面的示例代码中,我们使用了“SqlCommand”和“SqlDataReader”类来执行SQL查询并获取查询结果。最后,我们使用了“Response.Write”方法将结果输出到ASP.NET网页中显示。
注意,上面的示例代码中的数据库连接字符串需要您根据自己的SQL Server数据库进行修改。