Home   Cover Cover Cover Cover
 

Utlity-Klassen DBReader und DataSetPrinter


Zu Abschnitt 5.5.2 des Buchs

Die Hilfskalssen DBReader und DataSetPrinter werden im Beispiel DataSets und XML-Schemas für das Einlesen und Ausgeben des DataSets verwendet.

5-5-2-UtilityClasses.cs
using System;
using System.Data;
using System.Data.OleDb;

namespace Chapter5
{
    public class DBReader
    {

        static OleDbCommand GetSelectAllCmd()
        {
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = new OleDbConnection("provider=SQLOLEDB; " +
              " data source=(local)\\SQLEXPRESS; database=NETBOOK; user id=sa; password=sa;");
            cmd.CommandText = "SELECT * FROM Person; SELECT * FROM Contact";
            return cmd;
        }

        public static DataSet LoadDataFromDB()
        {
            DataSet ds = new DataSet("PersonContacts");
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = GetSelectAllCmd();
            //----- im DataSet befinden sich noch keine Tabellen, also fuege sie bei Fill hinzu!
            adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
            //----- Automatisch erzeugte Tabellen umbenennen
            adapter.TableMappings.Add("Table", "Person");
            adapter.TableMappings.Add("Table1", "Contact");
            //----- Daten aus der Datenbank laden
            adapter.Fill(ds);
            if (ds.HasErrors) ds.RejectChanges();
            else
            {
                DefineRelation(ds, adapter.SelectCommand.Connection);
                ds.AcceptChanges();
            }
            adapter.Dispose();
            return ds;
        }

        static void DefineRelation(DataSet ds, OleDbConnection conn)
        {
            DataTable schemaTable = null;
            //---- Fremdschluesselbeziehungen von Datenbank lesen
            try
            {
                if (conn.State != ConnectionState.Open) conn.Open();
                schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Foreign_Keys, null);
                conn.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            //---- Referentielle Integritaet im DataSet erstellen
            if (schemaTable != null)
            {
                foreach (DataRow r in schemaTable.Rows)
                {
                    DataTable parentTab = ds.Tables[r["PK_TABLE_NAME"].ToString()];
                    DataTable childTab = ds.Tables[r["FK_TABLE_NAME"].ToString()];
                    DataRelation rel = new DataRelation(
                        //Name der Beziehung im DataSet
                        parentTab.TableName + "_" + childTab.TableName,
                        // Vatertabelle, Spalte des Primaerschluessels
                        parentTab.Columns[r["PK_COLUMN_NAME"].ToString()],
                        //Abhaengige Tabelle, Spalte des Fremdschluessels
                        childTab.Columns[r["FK_COLUMN_NAME"].ToString()]);
                    ds.Relations.Add(rel);
                }
            }
        }
    }

    public class DataSetPrinter
    {

        public static void Print(DataSet ds)
        {
            Console.WriteLine("DataSet {0}:", ds.DataSetName);
            Console.WriteLine();
            foreach (DataTable t in ds.Tables)
            {
                Print(t);
                Console.WriteLine();
            }
        }

        public static void Print(DataTable t)
        {
            //---- Tabellenkopf
            PrintHeader(t);
            //---- Daten
            int nrOfCols = t.Columns.Count;
            foreach (DataRow row in t.Rows)
            {
                Print(row);
            }
        }

        public static void Print(DataRow row)
        {
            object[] items = row.ItemArray;
            for (int i = 0; i < items.Length; i++)
            {
                Console.Write(items[i]); Console.Write(" | ");
            }
            Console.WriteLine();
        }

        public static void PrintHeader(DataTable t)
        {
            Console.WriteLine("Tabelle {0}:", t.TableName);
            foreach (DataColumn col in t.Columns)
            {
                Console.Write(col.ColumnName + " | ");
            }
            Console.WriteLine();
            for (int i = 0; i < 40; i++) { Console.Write("-"); }
            Console.WriteLine();
        }

    }

}