Simple test example of connecting ASP.NET to SQL Server.

Here is a simple test example of ASP.NET connecting to 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/>");
                        }
                    }
                }
            }
        }
    }
}

The above code assumes that you have already created a database named DemoDB and have created a table named Customers within that database.

In an ASP.NET application, create a page named “Default.aspx” and place the above code in the page’s code file.

When visiting this page, it will connect to an SQL Server database, retrieve data from the Customers table, and display the data on the page.

bannerAds