Как читать таблицы из базы данных Access в хэш-таблицу в C # - PullRequest
0 голосов
/ 04 октября 2019

Я создаю приложение Windows Forms в C # с помощью Visual Studio.

Я пытаюсь заставить его сделать следующее ...

For every table in Database:    
       a.   If table name is Cows
              i.    For every row in this table
                  1.    Create a new item in ‘All_Animals’ dictionary where the Animals ID is the Dictionary Key 
                        and the Key’s value is a new cow object
       b.   If table name is Dogs
              i.    same as above …
       d.   Etc.

Я создал подпрограмму-классы для всех животных, при этом «Животное» является родительским классом.

Лучшее, что я могу сделать прямо сейчас, это:

    private static Dictionary<int, Animal> allAnimals = new Dictionary<int, Animal>();

    private void Get_table()
    {
        try
        {
            OleDbCommand cmd = null;

            //Creates an array of strings containing the table names
            String[] Animals = new string[] { "Cows", "Dogs", "Goats", "Sheep" };

            //Loop to search through each table for the ID (Cow = 0, Dogs = 1, etc)
            for (int i = 0; i < Animals.Length; i++)
            {
                //Concatenates the element from Animals (table name) to the SQL select-statement to search through that table's records
                cmd = new OleDbCommand("SELECT * FROM " + Animals[i].ToString(), conn);
                using (OleDbDataReader reader = cmd.ExecuteReader())
                {
                    //if the reader still has rows to read for that table
                    if (reader.HasRows)
                    {
                        //while the reader is reading
                        while (reader.Read())
                        {
                            ////for every row create a new object of this class using the column/field attributes
                            for (int j = 0; j < reader.FieldCount; j++)
                            {
                                //Create Dictionary key & create new object from table columns, store object as key's value - e.g. { "1001", "CowObj1001" }

                            }
                        }
                        break;
                    }
                    // else no data found for the ID shows feedback for user
                    else
                    { 
                        MessageBox.Show("No tables found");
                        break;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            error_msg = ex.Message;
            MessageBox.Show(error_msg);
        }
    }

Как мне получить идентификатор изпервый столбец, используйте это для создания нового ключа хеш-таблицы, а затем создайте и сохраните новый объект, используя остальные значения из столбцов в качестве значения этого ключа?

Я думаю, что есть также проблема в том, что каждыйТаблица имеет различные атрибуты ... Например,

Корова = ID, Количество воды, Суточная стоимость, Вес, Возраст, Цвет, Количество молока, Джерси

Овца = ID, Количествовода, суточная стоимость, вес, возраст, цвет, количество шерсти

Мои занятия ...

class Prices
{
    public static double milkPriceCow;
    public static double milkPriceGoat;
    public static double waterPrice;
    public static double sheepWoolPrice;
    public static double jersyTax;
    public static double taxPerKg;
}

abstract class Animal
{
    protected int id;
    protected double amtWater;
    protected double dailyCost;
    protected double weight;
    protected int age;
    protected string color;

    public Animal(int id, double amtWater, double dailyCost, double weight, int age, string color)
    {
        this.id = id;
        this.amtWater = amtWater;
        this.dailyCost = dailyCost;
        this.weight = weight;
        this.age = age;
        this.color = color;
    }
}

class Cow : Animal
{
    protected double amtMilk;
    protected bool isJersy;

    public Cow(int id, double amtWater, double dailyCost, double weight, int age, string color, double amtMilk, bool isJersy) : base(id, amtWater, dailyCost, weight, age, color)
    {
        this.amtMilk = amtMilk;
        this.isJersy = isJersy;
    }
}

class Goat : Animal
{
    protected double amtMilk;
    public Goat(int id, double amtWater, double dailyCost, double weight, int age, string color, double amtMilk) : base(id, amtWater, dailyCost, weight, age, color)
    {
        this.amtMilk = amtMilk;
    }
}

class Sheep : Animal
{
    protected double amtWool;
    public Sheep(int id, double amtWater, double dailyCost, double weight, int age, string color, double amtWool) : base(id, amtWater, dailyCost, weight, age, color)
    {
        this.amtWool = amtWool;
    }
}

class Dog : Animal
{
    public Dog(int id, double amtWater, double dailyCost, double weight, int age, string color) : base(id, amtWater, dailyCost, weight, age, color)
    {

    }
}

1 Ответ

0 голосов
/ 04 октября 2019

Возможно, вы используете метод расширения ?: если у вас есть что-то вроде этого: (не проверено)

    public abstract class Animal
        {
            public int id { get; private set; }
            public double amtWater { get; private set; }
            public double dailyCost { get; private set; }
            public double weight { get; private set; }
            public int age { get; private set; }
            public string color { get; private set; }

            public Animal(System.Data.IDataRecord record)
            {
                this.id = Convert.ToInt32(record["id"].ToString());
                this.amtWater = Convert.ToDouble(record["amtWater"].ToString());
                this.dailyCost = Convert.ToDouble(record["dailyCost"].ToString());
                this.weight = Convert.ToDouble(record["weight"].ToString());
                this.age = Convert.ToInt32(record["age"].ToString());
                this.color =  record["color"].ToString();
            }
        }
        public class Cow:Animal
        {
            public double amtMilk { get; private set; }
            public bool isJersy { get; private set; }
            public Cow(System.Data.IDataRecord record):base(record)
            {
                this.amtMilk = Convert.ToDouble(record["amtMilk"].ToString());
                this.isJersy = Convert.ToBoolean(record["isJersy"].ToString());
            }
        }
        public class Goat : Animal
        {
            public double amtMilk { get; private set; }
            public Goat(System.Data.IDataRecord record) : base(record)
            {
                this.amtMilk = Convert.ToDouble(record["amtMilk"].ToString()); 
            }
        }
        public class Sheep : Animal
        {
            public double amtWool { get; private set; }
            public Sheep(System.Data.IDataRecord record) : base(record)
            {
                this.amtWool = Convert.ToDouble(record["amtWool"].ToString());
            }
        }

и метод расширения

    public static class DataReaderX
            {
                public static Animal ToAnimal(this System.Data.IDataRecord record, string typeName)  
                {
                    var animal = (Animal)Activator.CreateInstance(Type.GetType($"{typeName}"), record);
                    return animal;
                }
    }

, тогда как вычитать данные, создавать "животное":

    private static Dictionary<int, Animal> allAnimals = new Dictionary<int, Animal>();
    public void Get_table(OleDbConnection conn)
            {
                String[] Animals = new string[] { "Cow", "Dog", "Goat", "Sheep" };
                foreach(string animaltype in Animals)
                {
                    using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM " + animal, conn))
                    {
                        using (OleDbDataReader reader = cmd.ExecuteReader())
                        {
                            if (!reader.HasRows)
                            {
                                //MessageBox.Show("No tables found");
                                continue;
                            }
                            while (reader.Read())
                            {
                                int someAnimalId = 0;//<---- your animal id;
                                var animal = reader.ToAnimal(animaltype);
                                allAnimals.Add(someAnimalId, animal);
                            }
                        }
                    }
                }
            }
...