我有一个用 C# 完成的 asp.net 项目(我的 C# 语法很生疏),我正在使用它在项目中创建的内置数据库。我创建了一个名为 aspnet_Tutorials 的表,它(目前)存储两列用户提交的数据:TutorialName 和 TutorialContent。很简单,这是一个学习项目。
我需要做的是从 aspnet_Tutorials 的第一列创建一个列表,以使用它在页面上创建教程的“目录”。我遇到问题的部分(主要是语法上)是连接到列并对其进行迭代以将值放入列表中。任何人都可以提供一个直接的例子吗?并可能解释代码中发生的事情。
public class TutorialsDirDAL
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
public List<string> DisplayTutorials() //parameters? String qry?
{
//query the database table, foreach loop over the data, place it into a list?
}
}
我知道如何编写简单的 sql 查询。但是我在谷歌搜索中看到了几个不同的设置。我目前有以下查询,请随意将其拆开或提供比使用查询更好的解决方案。
cmd.CommandText = "SELECT * FROM ASPNET_TUTORIALS (TutorialTitle)"
+ "VALUES (@tutorialTitle)";
谢谢!
最佳答案
ebad86 的回答是可以接受的,但由于您显然正在学习,我认为引入 OO 原则会使此时您尝试学习的内容变得困惑。
这是一个基本的方法:
private void GetData()
{
//The object that will physically connect to the database
using(SqlConnection cnx = new SqlConnection("<your connection string>")
{
//The SQL you want to execute
SqlCommand cmd = new SqlCommand("SELECT * FROM ASPNET_TUTORIALS");
//Open the connection to the database
cnx.Open();
//execute your command
using (IDataReader dataReader = cnx.ExecuteReader(cmd))
{
//Loop through your results
while(dataReader.Read())
{
//do whatever to the data
ListItem item = new ListItem(Convert.ToString(dataReader["TutorialName"]));
lst.Items.Add(item);
}
}
}
}
这一切都非常简单。不过,您最感兴趣的部分是 while 循环。循环将遍历所有返回的记录,您可以对它们做任何需要做的事情。在我的示例中,我假设有一个名为“lst”的列表框,我只是向其中添加 ListItems,其名称与“TutorialName”相同。此时您可以对数据做任何您需要做的事情。为了适合您的示例(返回列表),您可以这样做:
private List<string> GetData()
{
List<string> lst = new List<string>();
//The object that will physically connect to the database
using(SqlConnection cnx = new SqlConnection("<your connection string>")
{
//The SQL you want to execute
SqlCommand cmd = new SqlCommand("SELECT * FROM ASPNET_TUTORIALS");
//Open the connection to the database
cnx.Open();
//execute your command
using (IDataReader dataReader = cnx.ExecuteReader(cmd))
{
//Loop through your results
while(dataReader.Read())
{
lst.Add(Convert.ToString(dataReader["TutorialName"]));
}
}
}
return lst;
}
如有问题请回复。
关于c# - asp.net C# 数据库表列列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11414504/