System.Data.Common.DbDataReader [英] System.Data.Common.DbDataReader
本文介绍了System.Data.Common.DbDataReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我使用这个类做了
SELECT * FROM ...
针对数据库,我应该用什么方法或变量此类只是为了给我从SQL语句?
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?
推荐答案
在使用的DbDataReader你需要遍历所有的结果是这样的:
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();
}
这将产生一个基本的CSV文件。
This will generate a basic CSV file.
这篇关于System.Data.Common.DbDataReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文