简体   繁体   English

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

[英]How do I create a csv file with the output of sql query?

How do I create a CSV file with the output of a SQL (SQLServer) query in C#?如何使用 C# 中的 SQL (SQLServer) 查询的输出创建 CSV 文件?

Here is the code I have tried so far:这是我到目前为止尝试过的代码:

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]));
    }
  }
}

But I am getting errors on the line:但我在线上收到错误:

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

Errors:错误:

Error 1 The best overloaded method match for 'System.Collections.Generic.List.Add(string)' has some invalid arguments错误 1 ​​'System.Collections.Generic.List.Add(string)' 的最佳重载方法匹配有一些无效参数

Error 2 Argument 1: cannot convert from 'System.Data.SqlClient.SqlDataReader' to 'string'错误 2 参数 1:无法从“System.Data.SqlClient.SqlDataReader”转换为“string”

Error 3 The best overloaded method match for 'System.Data.SqlClient.SqlCommand.ExecuteReader(System.Data.CommandBehavior)' has some invalid arguments错误 3 'System.Data.SqlClient.SqlCommand.ExecuteReader(System.Data.CommandBehavior)' 的最佳重载方法匹配有一些无效参数

Error 4 Argument 1: cannot convert from 'string' to 'System.Data.CommandBehavior'错误 4 参数 1:无法从“字符串”转换为“System.Data.CommandBehavior”

I followed this post to do this.我按照这篇文章来做到这一点。

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();
}

You havent tried anything so here is a little motivation to get you started.你还没有尝试过任何东西,所以这里有一点让你开始的动力。

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");

This is give you timeout for tables containing large data but hey i am little less lazy than you.这是给你包含大量数据的表的超时时间,但嘿,我没有你那么懒惰。 So figure it out.所以想办法。 Hope it helps good luck.希望它有助于好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在CSV文件的Linq查询中检查字符是否存在? - How do I check for the existence of a character in a Linq query on a CSV file? 如何使用 SQL 之类的“IN”语句创建 LinQ 查询? - How do I create a LinQ query with an “IN” statement like SQL? 如何在NHibernate中使用sql查询创建表? - How Can I Do Create Table by using sql query in NHibernate? 我如何将 csv 文件中的数据排序为标准化的 output,同时读取标题以对数据进行排序 - How do i sort data in a csv file to a standardized output, While reading headers to sort data 如何从CSV文件中选择前4列并运行查询 - how do i select the first 4 columns from my CSV file and run a query 我如何创建将从.csv文件中读取键和值的AC#词典 - How do i create a c# dictionary that will read in key and values from .csv file 如何在LINQ to SQL查询中输出大写的列? - How do you output a column in Upper Case in a LINQ to SQL Query? 如何创建具有SQL连接和查询功能的类并将其调用到Windows窗体按钮? - How do I create a class with SQL connection and query functions and calling it to my windows form buttons? 如何将SQL查询转换为Lambda? - How do I convert SQL Query to Lambda? 如何将此查询更改为linq到sql? - How do I change this query to linq to sql?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM