C # - class for general database connection, command, reader

Suppose I am developing a class that can process any database technology to create a connection, execute a command, and receive data, etc.

If I need to create a common database processing class for existing RDBMS (for example, SQL Server, Oracle, FireBird, etc.) that .net abstract-class / Interface should use {DbConnection, DbCommand, DbParameter, ...} or {IDbConnection, IDbCommand, IDbParameter, ...}?

Should I use code like

public bool CreateConnection(DatabaseTypeEnum type)
{
    DbConnection conn ;

    if(type==DatabaseTye.Oracle)
    {
        //....
    }    
}

public DbDataReader GetData()
{

    DbCommand comm;
    //...
}

or,

public bool CreateConnection(DatabaseTypeEnum type)
{
    IDbConnection conn ;

    if(type==DatabaseTye.Oracle)
    {
        //....
    } 
}

public IDbDataReader GetData()
{

    IDbCommand comm;
    //...
}

And why?

+3
source share
3 answers

Ermm ... a completely different question :)

OK no ...

, ... switch/if :).

Factory, , SQL Server DB2 Oracle - .

IDbConnection, IDbCommand .. (DbConnection, DbCommand ..). , (, SqlDataReader ), .

Factory switch/if , . app.config. , app.config , , Factory .

: this. DbProviderFactory ...

+5

?

:

public class DBHelper<T, Y, W> where T: DbConnection, new() where Y : DbCommand, new()
{
        private T conn_ = new T();
        private Y comm_ = new Y();            
}

, , .

0

IDbConnection IDbCommand, ( ADO.NET), , . IDbConnection IDbCommand. :

public class Db<T> where T : IDbConnection, new()
{
    public bool CreateConnection()
    {
        T conn;

        //now you dont need these lines since you dont have to worry about
        //what type of db you are using here, since they all implement
        //IDbConnection, and in your case its just T.
        //if(type==DatabaseTye.Oracle)
        //{
            //....
        //}
    }

    public DbDataReader GetData()
    {
        //get comm object from S conn
        using(var conn = new S())
            using (var comm = conn.CreateCommand())

        //...
    }

The advantage is that you can pass to this class the types that you want to use for DbConnectionand DbCommandthat will be different for the MySQL.net and Oracle one connector. So you have some kind of control outside the classroom. You can read this question and my answer for reference on a basic implementation.

0
source

Source: https://habr.com/ru/post/1712264/


All Articles