简体   繁体   中英

IDataReader for Generic Access

I'm trying to make a "Helper" class where you simply pass the driver and the parameters and the class does the connection and connection string assembly for you.

I've been using the interfaces from System.Data like IDataReader, IDbConnection.

Now after testing it with MySQL the code is working perfectly but as soon as I point and configure it for SQL Server (Microsoft) it does not return any processed rows. I have done some debugging and the info from the SQL server is appearing in the IDataReader but it seems I can't Iterate over it ?

My Current Code:

Connect Method in Helper Class

try
{
    factory = System.Data.Common.DbProviderFactories.GetFactory(driver);
    _con = factory.CreateConnection();
    _con.ConnectionString = buildConnectionString.ToString();
    _con.Open();
}
catch (System.Data.Common.DbException ex)
{
    _con = null;
    throw ex;
}
catch (Exception ex)
{
    _con = null;
    throw ex;
}
return _con;

A the moment I'm passing my driver as System.Data.SqlClient for SQL Server and MySql.Data.MySqlClient for MySQL.

System.Data.IDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
while (reader.Read())
{
    System.Data.DataRow row = table.NewRow();
    // Insert info from Reader into the Row
    table.Rows.Add(row);
}

reader.Close();

I suspects it has something to do with how IDataReader is trying to handle the types but can't find any documentation on this as it's working perfectly for MySQL but not for SQL Server? Any Help?

You aren't giving many clues here, since most of the interesting code here is probably around the command setup. If, at execution, it never enters the while (reader.Read()) {...} block, then it is probably TSQL or parameter related (especially nulls, which can easily result in no rows).

Since your data is DataTable -centric and you already have the provider-factory, another possibility here is to use CreateDataAdapter() from the factory, and let the factory worry about the binding of TSQL to a DataTable . Otherwise, treble-check that the TSQL you are providing is valid, sensible, and correctly parameterised.

Ultimately, the Read() loop itself is fine, and is pretty-much what all materialization routines do. It is, for example, very close to how dapper works, and that works fine over a range of databases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM