Computerlinguistik - und mehr.

ADO.NET offers pretty good support for retrieval of database schema information, independent of the provider in use.

For example, you can use something like this to retrieve all registered factory classes, select a factory and then get a list of all tables:

// Get all providers
DataTable factoryClasses = DbProviderFactories.GetFactoryClasses( );

// Select a provider
DbProviderFactory factory = DbProviderFactories.GetFactory( factoryClasses.Rows[0] );

// Create a connection
using(DbConnection connection = factory.CreateConnection())
    // Set the connection string
    connection.ConnectionString = connectionString;
    // Open the connection
    connection.Open( );

    // Retrieve table information,
    // table names are in column "TABLE_NAME"
    DataTable tableInfo = connection.GetSchema("Tables");

Works like a charm.
Now you may feel tempted to use the same approach to retrieve column information:

// We're only interested in columns for this table
string[] restrictions = new[] { null, null, tableName };

// Retrieve column information
DataTable columnInfo = connection.GetSchema("Columns", restrictions);

At a first glance, this, too, works.
However, the value in the DATA_TYPE column will be provider-specific, making any abstraction pretty much worthless.

But there is a way out:

// Create a command
using( DbCommand command = connection.CreateCommand( ) )
    // The WHERE part is obsolete if you have a decent
    // database like MSSQL that correctly interprets
    // the CommandBehavior.
    command.CommandText = string.Format( "SELECT * FROM {0} WHERE 1=2", tableName );

    // Execute the command and retrieve schema information
    using( DbDataReader reader = command.ExecuteReader( CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly ) )
        // Retrieve column information
        DataTable columnInfo = reader.GetSchemaTable( );

        // Et voilà, provider-independent data types
        DataRow row = columnInfo.Rows[0];
        Type dataType = ( Type )row[ "DataType" ];

Experiment: Textsorten

Wir führen ein witziges und kurzes linguistisches Experiment zu Textsorten durch.
Wenn Du 2-3 Minuten hast, kannst Du mir und der Linguistik einen Gefallen tun, indem Du teilnimmst und mir die Ergebnisse per Email oder über das Kontaktformular schickst.

Vielen Dank! Smile

Hier geht's zum Experiment:

Experiment Textsorten - Set B.pdf (21,44 kb)


    Über den Autor


    Computerlinguist, stärkenorientierter Coach, Kampfsportler.