-1

我有一个数据库表。这个表不经常更改。但我需要从该表中检索数据。我的要求是当应用程序启动时,它会读取该表的所有记录并将其存储到数据表中。所以,当需要时,我只是从数据表而不是数据库中查询记录。我已经写好了代码。现在我的问题是:** **当我调用该方法时,是每次都向数据库查询此代码并每次创建 DataTable 还是首先从 db 中获取数据一次并将其存储到数据表中,直到应用程序关闭?* *** 如果不是,请帮我解决。

static void Main(string[] args)
{
    String RoomNumber = GetTable("xi");
    Console.WriteLine(RoomNumber);
    Console.ReadLine();
}

static string GetTable(string ShortCode)
{
    DataTable table = new DataTable();
    DataColumn column;
    DataRow row;

    column = new DataColumn();
    column.DataType = Type.GetType("System.String");
    column.ColumnName = "Class";
    table.Columns.Add(column);

    column = new DataColumn();
    column.DataType = Type.GetType("System.String");
    column.ColumnName = "RoomNumber";
    table.Columns.Add(column);

    SqlConnection thisConnection = new SqlConnection(conn);
    thisConnection.Open();

    SqlCommand thisCommand = thisConnection.CreateCommand();
    thisCommand.CommandText = "SELECT Class,RoomNumber FROM Section ";
    SqlDataReader thisReader = thisCommand.ExecuteReader();
    while (thisReader.Read())
    {
        row = table.NewRow();

        row["Class"] = thisReader["Class"].ToString();
        row["RoomNumber"] = thisReader["RoomNumber"].ToString();
        table.Rows.Add(row);
    }
    thisConnection.Close();

    DataRow[] result = table.Select("Class='" + Class + "'");
    foreach (DataRow dataRow in result)
    {
        RoomNumber = dataRow[1].ToString();
        //Console.WriteLine("{0}, {1}", dataRow[0], dataRow[1]);
    }

    //Console.WriteLine(RoomNumber);

    return RoomNumber;
}
4

1 回答 1

0

这将在程序启动时将数据库中的数据加载到您的 DataTable 中,并且假设您没有在任何其他地方调用 GetTable 方法,它将只运行一次。

于 2013-09-16T08:37:57.663 回答