阅读量:2
以下是ASP.NET连接SQL Server的简单测试实例:
using System;
using System.Data.SqlClient;
namespace DemoApp
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = "Data Source=(local);Initial Catalog=DemoDB;Integrated Security=True";
string query = "SELECT * FROM Customers";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string customerName = reader["CustomerName"].ToString();
string contactName = reader["ContactName"].ToString();
string city = reader["City"].ToString();
// 做你想做的事情,比如把数据显示在页面上
Response.Write($"CustomerName: {customerName}, ContactName: {contactName}, City: {city}
");
}
}
}
}
}
}
}
上述代码假设你已经创建了一个名为DemoDB的数据库,并且在该数据库中已经创建了一个名为Customers的表。
在ASP.NET应用程序中,创建一个名为"Default.aspx"的页面,并将上述代码放在该页面的代码文件中。
当访问该页面时,它将连接到SQL Server数据库,从Customers表中检索数据,并将数据显示在页面上。
以上就是关于“ASP.NET连接SQLServer简单测试实例”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm