您的位置:宽带测速网 > 网络知识 > ASP.NET连接SQLServer简单测试实例

ASP.NET连接SQLServer简单测试实例

2025-06-21 09:04来源:互联网 [ ]

以下是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}<br/>");}}}}}}}

上述代码假设你已经创建了一个名为DemoDB的数据库,并且在该数据库中已经创建了一个名为Customers的表。

在ASP.NET应用程序中,创建一个名为"Default.aspx"的页面,并将上述代码放在该页面的代码文件中。

当访问该页面时,它将连接到SQL Server数据库,从Customers表中检索数据,并将数据显示在页面上。