using System;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
namespace PullData
{
class Program
{
static void Main(string[] args)
{
OleDbConnection connLocal = new OleDbConnection("Provider=SAOLEDB.10;Data Source=demo;Persist Security Info=True;User ID=dba;PWD=sql;Location=1.2.3.4");
OleDbCommand cmdLocal = new OleDbCommand("SELECT tran_num, provider_id, amount, tran_date, collections_go_to, impacts, type, 'TestClinic' AS Clinic FROM transactions WHERE tran_date > '2015-09-27'", connLocal);
StreamWriter sqlWriter = new StreamWriter(@"C:\Users\Administrator\Desktop\Clinic.txt");
try
{
connLocal.Open();
}
catch (Exception connerr) { Debug.WriteLine(connerr.Message); }
OleDbDataReader readLocal = cmdLocal.ExecuteReader();
while (readLocal.Read())
{
sqlWriter.WriteLine("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}", readLocal.GetValue(0).ToString(), readLocal.GetValue(1).ToString(), readLocal.GetValue(2).ToString(), readLocal.GetValue(3).ToString(), readLocal.GetValue(4).ToString(), readLocal.GetValue(5).ToString(), readLocal.GetValue(6).ToString(), readLocal.GetValue(7).ToString());
}
readLocal.Close();
connLocal.Close();
}
}
}
嘿所有,
以上是我目前正在测试将查询结果写入txt文件的代码。除了每次尝试运行它之外,所有似乎都有效,它似乎在结束程序之前停止在随机点写入。运行的查询有3370行,以tran_num 227239结尾但是我的txt文件的末尾在到达之前结束并且在这样的行中间被截断:
227233|999|-5.00|11/3/2015 12:00:00 AM|999|C|A|TestClinic
227234|AK|0.00|11/3/2015 12:00:0
我试图用同样的问题运行这几次,我已经将查询运行到数据库(使用相同的应用程序)并且可以看到所有行。有关为什么会发生这种情况的任何想法?感谢
答案 0 :(得分:2)
如果出现异常,您应该使用using语句确保您的一次性对象也被关闭。此外,要确保在完成写入后将所有内容刷新到磁盘,请调用StreamWriter Flush方法
static void Main(string[] args)
{
using(OleDbConnection connLocal = new OleDbConnection(...))
using(OleDbCommand cmdLocal = new OleDbCommand("SELECT tran_num, provider_id, amount, tran_date, collections_go_to, impacts, type, 'TestClinic' AS Clinic FROM transactions WHERE tran_date > '2015-09-27'", connLocal))
using(StreamWriter sqlWriter = new StreamWriter(@"C:\Users\Administrator\Desktop\Clinic.txt"))
{
try
{
connLocal.Open();
using(OleDbDataReader readLocal = cmdLocal.ExecuteReader())
{
while (readLocal.Read())
{
sqlWriter.WriteLine("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}",
readLocal.GetValue(0).ToString(),
readLocal.GetValue(1).ToString(),
readLocal.GetValue(2).ToString(),
readLocal.GetValue(3).ToString(),
readLocal.GetValue(4).ToString(),
readLocal.GetValue(5).ToString(),
readLocal.GetValue(6).ToString(),
readLocal.GetValue(7).ToString());
}
}
sqlWriter.Flush();
}
catch (Exception connerr) { Debug.WriteLine(connerr.Message); }
}
}
另请注意,我已将所有代码包含在try / catch中,而不仅仅是打开连接并删除了对Close的调用,因为当您从using块中退出时会自动调用它。