开发者

System.Data.Common.DbDataReader

If I use 开发者_开发技巧this class to do a

SELECT * FROM ...

statement against a database, what method or variable of this class should I use just to give me a dump of the output from the SQL statement?


When using a DbDataReader you'll need to iterate over all the results like this:

using (DbDataReader dataReader = dbCommand.ExecuteReader())
{
    while (dataReader.Read())
    {
        // Get the values of the fields in the current row
        // For example, if the first column is a string...
        string firstColumn = dataReader.GetString(0);
    }

    dataReader.Close();
}

If you are trying to output the results to a file, a very naive approach would be something like this:

using (StreamWriter streamWriter = new StreamWriter(path))
{
    using (DbDataReader dataReader = command.ExecuteReader())
    {
        while (dataReader.Read())
        {
            for (int index = 0; index < dataReader.FieldCount; index++)
            {
                streamWriter.Write(dataReader.GetValue(index));

                if (index < dataReader.FieldCount - 1)
                {
                    streamWriter.Write(',');
                }
                else
                {
                    streamWriter.WriteLine();
                }
            }
        }

        dataReader.Close();
    }

    streamWriter.Close();
}

This will generate a basic CSV file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜