在ASP.NET中,我们可以使用ADO.NET来连接和查询数据库。以下是一个示例代码,演示如何从数据库获取数据:
string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("SELECT * FROM Customers", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string customerName = reader["CustomerName"].ToString();
string contactName = reader["ContactName"].ToString();
string city = reader["City"].ToString();
// 在这里使用数据,可以将其添加到GridView或其他控件中
}
reader.Close();
}
在上面的代码中,我们首先获取连接字符串,然后创建一个SqlConnection对象。接下来,我们创建一个SqlCommand对象,使用SELECT查询检索所需的数据。然后我们打开连接并使用ExecuteReader方法来获取一些数据。最后,我们循环读取数据并将其存储在变量中,或将其添加到控件中。
注意,这只是一个简单的示例,您应该使用参数化查询来避免SQL注入攻击。此外,您还可以使用ORM(对象关系映射)工具,例如Entity Framework或NHibernate来更轻松地连接和查询数据库。