using (var connection = new SqlConnection("user id=xxx;" +
"password=xxx;server=xxx;" +
"Trusted_Connection=yes;" +
"database=xxx; " +
"connection timeout=30"))
{
connection.Open();
string sql = "SELECT * FROM testTable";
using (var command = new SqlCommand(sql, connection))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
.
.
.
.
.
}
}
}
}
上面的代码可用于检索记录行列表并在我的C#控制台应用程序中显示它们,但在Main方法中会非常混乱。我想知道如何处理这些记录并通过调用方法将它们存储到列表或其他内容中。是否可以在C#控制台应用程序中使用?
答案 0 :(得分:25)
不知道数据库表中的内容,我将作一个例子:
帐户类:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
现在,您可以让reader
循环填充每个Person
,如下所示:
while (reader.Read())
{
var person = new Person();
person.FirstName = reader["FirstName"].ToString();
person.LastName = reader["LastName"].ToString();
person.Age = Convert.ToInt32(reader["Age"]);
}
最后,我们要构建一个要返回的Person
个对象的列表,如下所示:
var listOfPerson = new List<Person>();
while (reader.Read())
{
var person = new Person();
person.FirstName = reader["FirstName"].ToString();
person.LastName = reader["LastName"].ToString();
person.Age = Convert.ToInt32(reader["Age"]);
listOfPerson.Add(person);
}
return listOfPerson;
完整代码:
public List<Person> LoadPeople()
{
var listOfPerson = new List<Person>();
using (var connection = new SqlConnection("user id=xxx;" +
"password=xxx;server=xxx;" +
"Trusted_Connection=yes;" +
"database=xxx; " +
"connection timeout=30"))
{
connection.Open();
string sql = "SELECT * FROM testTable";
using (var command = new SqlCommand(sql, connection))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var person = new Person();
person.FirstName = reader["FirstName"].ToString();
person.LastName = reader["LastName"].ToString();
person.Age = Convert.ToInt32(reader["Age"]);
listOfPerson.Add(person);
}
}
}
}
return listOfPerson;
}
答案 1 :(得分:1)
您可以使用所需的属性创建自定义类,然后在每条记录中创建对象并将其添加到列表中。如果要打印sql语句中给出的任何结果,则可以执行以下操作。
using (var connection = new SqlConnection(connectionString))
using (var adapter = new SqlDataAdapter(sql, connection))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("--- Row ---");
foreach (var item in row.ItemArray)
{
Console.Write("Item: ");
Console.WriteLine(item);
}
}
}
答案 2 :(得分:1)
Read()方法读取您正在访问的数据(表),因此您可以将其保存到列表中。
这里我假设行中的数据是字符串
list<string> firstRow = new list<string>;
list<string> secondRow = new list<string>;
//in your while(reader.Read()) code . . .
while (reader.Read())
{
firstRow.Add(reader[0].ToString());
secondRow.Add(reader[1].ToString());
}
希望这有帮助。