【问题标题】:How to implement IDataReader?如何实现 IDataReader?
【发布时间】:2013-05-22 23:48:12
【问题描述】:

我的 XML 看起来像这样:

<resultset>
    <datarow>
        <datacol>Row 1 - Col 1</datacol>
        <datacol>Row 1 - Col 2</datacol>
        <datacol>Row 1 - Col 3</datacol>
        ...
    </datarow>
    ...
</resultset>
...

我的问题是,如何使用这个 XML 实现 IDataReader 接口?我迷路了……

我已经开发了这个:

public sealed class SybaseDataReader : IDataReader
{
    private DataSet _dataSet = new DataSet();

    #region IDataReader methods implementation
    // ...
}

我走的很好?

感谢您提供建设性且解释清楚的帖子。

【问题讨论】:

标签: c# ado.net implementation


【解决方案1】:

我写了一个简单的文件阅读器实现。您可以轻松地调整它以读取 xml 文件:

public class MyFileDataReader : IDataReader
{
    protected StreamReader Stream { get; set; }
    protected object[] Values;
    protected bool Eof { get; set; }
    protected string CurrentRecord { get; set; }
    protected int CurrentIndex { get; set; }

    public MyFileDataReader(string fileName)
    {
        Stream = new StreamReader(fileName);
        Values = new object[this.FieldCount];
    }  

请记住,IDataReader 有几种方法,您不需要根据您的场景实现这些方法。但可能有一些方法实现是你无法避免的:

 public void Close()
    {
        Array.Clear(Values, 0, Values.Length);
        Stream.Close();
        Stream.Dispose();
    }

    public int Depth
    {
        get { return 0; }
    }

    public DataTable GetSchemaTable()
    {
        // avoid to implement several methods if your scenario do not demand it
        throw new NotImplementedException();
    }

    public bool IsClosed
    {
        get { return Eof; }
    }

    public bool NextResult()
    {
        return false;
    }

    public bool Read()
    {
        CurrentRecord = Stream.ReadLine();            
        Eof = CurrentRecord == null;

        if (!Eof)
        {
            Fill(Values);
            CurrentIndex++;
        }

        return !Eof;
    }

    private void Fill(object[] values)
    { 
       //To simplify the implementation, lets assume here that the table have just 3         
       //columns: the primary key, and 2 string columns. And the file is fixed column formatted 
      //and have 2 columns: the first with width 12 and the second with width 40. Said that, we can do as follows

        values[0] = null;
        values[1] = CurrentRecord.Substring(0, 12).Trim();
        values[2] = CurrentRecord.Substring(12, 40).Trim();

       // by default, the first position of the array hold the value that will be  
       // inserted at the first column of the table, and so on
       // lets assume here that the primary key is auto-generated
        // if the file is xml we could parse the nodes instead of Substring operations
    } 

    public int RecordsAffected
    {
        get { return -1; }
    } 

要实现 IDataReader,还必须实现 IDisposable 和 IDataRecord 接口。

IDisposable 很简单,但 IDataRecord 可能很痛苦。同样,在这种情况下,我们无法避免一些方法实现:

 public int FieldCount
    {
        get { return 3;//assuming the table has 3 columns }
    }

    public IDataReader GetData(int i)
    {
        if (i == 0)
            return this;

        return null;
    }

    public string GetDataTypeName(int i)
    {
        return "String";
    }

    public string GetName(int i)
    {
        return Values[i].ToString();
    }

    public string GetString(int i)
    {
        return Values[i].ToString();
    }

    public object GetValue(int i)
    {
        return Values[i];
    }

    public int GetValues(object[] values)
    {
        Fill(values);

        Array.Copy(values, Values, this.FieldCount);

        return this.FieldCount;
    }

    public object this[int i]
    {
        get { return Values[i]; }
    }  

希望对你有帮助。

【讨论】:

    【解决方案2】:

    将 DataSet 作为 System.Data.IDataReader 的成员是不合逻辑的。

    最好考虑 XmlDocumnet、XDocument 或 XmlReader。

    【讨论】:

    • @Arnaud:实现 DataReader 并不简单。您必须提供GetSchema()Read()。最好先考虑一下您将如何做到这一点。
    • @Arnaud:更好的是,您真的需要 DataReader 吗?我有点怀疑。
    • IDbCommand.ExecuteQuery() 返回一个 DataReader,我需要取回查询的结果,所以是的,我认为我需要它(即使我一开始没有实现所有方法)。你有更好的主意吗?
    • 我们沿着树走。为什么需要 ExecuteQuery (ExecuteDataReader)?
    • Sybase ASE 不提供使用 Compact Framework 检索数据的方法,因此我开发了一个 UNIX 守护程序,它获取请求并以 XML 形式返回结果集。所以我开发了“SybaseConnection : IDbConnection”、“SybaseCommand : IDbCommand”、“SybaseDataReader : IDataReader”;-)
    【解决方案3】:

    这可能会有所帮助...

     //1. Create dataset
            var ds = new DataSet("A Dataset");
            var table = ds.Tables.Add("A Table");
            table.Columns.Add("Id", typeof(int));
            table.Columns.Add("Description", typeof(string));
    
            //2. Serialize as xml
            ds.WriteXml(@"C:\temp\dataset.xml");
    
            //3. Go look at the xml file's contents.
            //Your xml needs to be translated into this schema. 
            //You will have to write this. (Boring transform work...)
            //Dataset deserialization does not work with arbitrary xml documuents.
    
    
            //4. Loading the xml file
            var ds2 = new DataSet();
            ds2.ReadXml(@"C:\temp\dataset.xml");
    
            //Suggestion. Investigate using LINQ-to-xml. It would be easier to 
            //read the data from your xml schema. You could also load the Dataset tables row by row
            //using this type of approach 
    
            //1. Load xml data into an XElement.
            var element = XElement.Parse(@"<resultset>
                <datarow>
                    <datacol>Row 1 - Col 1</datacol>
                    <datacol>Row 1 - Col 2</datacol>
                    <datacol>Row 1 - Col 3</datacol>
                </datarow>
            </resultset>
            ");
    
            //2. Create a dataset
            ds = new DataSet("A Dataset");
            table = ds.Tables.Add("A Table");
            table.Columns.Add("Col1", typeof(string));
            table.Columns.Add("Col2", typeof(string));
            table.Columns.Add("Col3", typeof(string));
    
            //3. Walk XElements and add rows to tables
            foreach (var row in element.Elements("datarow"))
            {
                var r = table.NewRow();                
                table.Rows.Add(r);
                int i = 0;
                foreach (var columnValue in row.Elements("datacol"))
                {
                    r[i++] = columnValue.Value;
                }
            }         
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      相关资源
      最近更新 更多