c#查询到txt

时间:2015-11-29 16:46:03

标签: c# sql

我正在阅读这里的例子:

https://msdn.microsoft.com/en-us/library/fksx3b4f.aspx

想要做一个选择并将其写入文件的测试阅读:

void wait() {
    /* the next line was added to avoid count being accessed simultaneously, vvv */
    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 10)); // <---
    while (count <= 0); /* BUSY WAIT */
    --count;
}

但我不能因为&#39; SqlDataReader&#39;不包含&#39; ReadToEnd&#39;的定义没有扩展方法&#39; ReadToEnd&#39;接受类型&#39; SqlDataReader&#39;的第一个参数。可以找到。

那么我怎样才能将这个简单的选择变成一个像这样的输出的txt文件?

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;

cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
 System.IO.File.WriteAllText(@"C:\stupidtest\customers.txt", reader.ReadToEnd());
sqlConnection1.Close();

如果我使用:

dasdgdsgsdg     asgasg    sadgasdgasdg          agdsfg
sdasdgasdgasgg  sdfasdfa  sadfasdfasdgasdgasdg  sadgasgdgda
a               asd       gdgasdg               asdfgghh

我可以实现吗?

1 个答案:

答案 0 :(得分:0)

类似的东西:

static string ReadToEnd(this SqlDataReader rdr){
    StringBuilder MyStringBuilder = new StringBuilder();
    while (rdr.Read())
    {
        String line = "";
        for(int i=0;i<rdr.FieldCount;i++)
        {
            line+=rdr.GetString(i)+@"\t";

        }
        MyStringBuilder.AppendLine(line);
    }
    return MyStringBuilder.ToString();
}