如何使用sql查询的输出创建csv文件?

时间:2014-09-24 07:20:56

标签: c#

如何使用C#中的sql(SQLServer)查询输出创建csv文件?

这是我到目前为止尝试过的代码:

public static void CreateManifestFile(string SQLFileToExecute, string ConnectionString, StreamWriter logfile)
{
    int success = 0;
    List<string> results = new List<string>();
    string script = File.ReadAllText(@SQLFileToExecute);
    Logging.WriteToLog(" ", logfile);
    Logging.WriteToLog(" ", logfile);
    Logging.WriteToLog("=== Processing file: [" + SQLFileToExecute + "] ===", logfile);

    // split script on GO command
    IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);

    SqlConnection Connection = new SqlConnection(ConnectionString);
    Connection.Open();

    Connection.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e)
    {
        Logging.WriteToLog("Msg: " + e.Message, logfile);
        success = 1;
    };
    SqlCommand sqlcmd = new SqlCommand();
    sqlcmd.Connection = Connection;
    foreach (string commandString in commandStrings)
    {
        if (commandString.Trim() != "")
        {
            success = 0;
            Console.WriteLine(commandString.ToString());
            logfile.WriteLine(commandString.ToString());
            results.Add(sqlcmd.ExecuteReader(commandString));
            if (success == 0)
            {
                Logging.WriteToLog("Command executed successfully.", logfile);
            }
        }
    }
    Connection.Close();
    int length = results.Count;
    string delimter=",";
    using(System.IO.TextWriter writer = File.CreateText("manifest.csv"))
    {
        Logging.WriteToLog("manifest count:" + length, logfile);
        for(int index = 0; index < length; index++)
        {
            writer.WriteLine(string.Join(delimter,results[index]));
        }
    }

}

但我收到了错误:

results.Add(sqlcmd.ExecuteReader(commandString));

错误:

  

错误1最佳重载方法匹配   &#39; System.Collections.Generic.List.Add(字符串)&#39;有一些无效的   参数

     

错误2参数1:无法转换   &#39; System.Data.SqlClient.SqlDataReader&#39;到&#39;字符串&#39;

     

错误3最佳重载方法匹配   &#39; System.Data.SqlClient.SqlCommand.ExecuteReader(的System.Data.CommandBehavior)&#39;   有一些无效的论点

     

错误4参数1:无法转换为&#39; string&#39;至   &#39;的System.Data.CommandBehavior&#39;

我跟着this post执行此操作。

2 个答案:

答案 0 :(得分:1)

public string ExportToCSVFile(DataTable dtTable)
{
    StringBuilder sbldr = new StringBuilder();
    if (dtTable.Columns.Count != 0)
    {
        foreach (DataColumn col in dtTable.Columns)
        {
            sbldr.Append(col.ColumnName.Replace(",", "") + ',');
        }
        sbldr.Append("\r\n");
        foreach (DataRow row in dtTable.Rows)
        {
            foreach (DataColumn column in dtTable.Columns)
            {
                sbldr.Append(row[column].ToString().Replace(",", "").Trim() + ',');
            }
            sbldr.Append("\r\n");
        }
    }
    return sbldr.ToString();
}

答案 1 :(得分:0)

你没有尝试过任何事情,所以这里有一点动力让你开始。

SqlServerStorage storage = new SqlServerStorage(typeof(Order));
string sqlConnectionString ="Server=SqlServer;Database=SqlDataBase;Trusted_onnection=True";
storage.ConnectionString = sqlConnectionString;
storage.SelectSql = "select * from Yourtable";
storage.FillRecordCallback = new FillRecordHandler(FillRecordOrder);
FileDataLink link = new FileDataLink(storage);
link.FileHelperEngine.HeaderText = headerLine;
link.ExtractToFile("file.csv");

这会给你包含大数据的表超时,但是我比你懒得多。弄清楚。希望它有助于好运。