以下是ASP.NET連接SQL Server的簡(jiǎn)單測(cè)試實(shí)例:
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();
// 做你想做的事情,比如把數(shù)據(jù)顯示在頁(yè)面上
Response.Write($"CustomerName: {customerName}, ContactName: {contactName}, City: {city}<br/>");
}
}
}
}
}
}
}
上述代碼假設(shè)你已經(jīng)創(chuàng)建了一個(gè)名為DemoDB
的數(shù)據(jù)庫(kù),并且在該數(shù)據(jù)庫(kù)中已經(jīng)創(chuàng)建了一個(gè)名為Customers
的表。
在ASP.NET應(yīng)用程序中,創(chuàng)建一個(gè)名為"Default.aspx"的頁(yè)面,并將上述代碼放在該頁(yè)面的代碼文件中。
當(dāng)訪問該頁(yè)面時(shí),它將連接到SQL Server數(shù)據(jù)庫(kù),從Customers
表中檢索數(shù)據(jù),并將數(shù)據(jù)顯示在頁(yè)面上。