开发者

System.Data.Common.DbDataReader

开发者 https://www.devze.com 2022-12-28 16:25 出处:网络
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 stat

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

精彩评论

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

关注公众号