如何在C#中使用sql(SQLServer)查詢的輸出創建csv文件?如何使用sql查詢的輸出創建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最佳重載方法匹配 'System.Collections.Generic.List.Add(string)'有一些無效的 參數
錯誤2參數1:不能從 'System.Data.SqlClient.SqlDataReader' 到 '字串'
錯誤3爲 「System.Data.SqlClient.SqlCommand.ExecuteReader最好重載的方法匹配(轉換的System.Data.CommandBehavior)」 有一些無效參數
錯誤4參數1:不能從轉換 '字符串' 到 '的System.Data.CommandBehavior'
我FOL低於this post來做到這一點。
你嘗試過什麼嗎? – 2014-09-24 07:22:38
對不起,但'-1'爲零努力。 – 2014-09-24 07:23:11
如果您有任何問題,請發佈您的代碼或您迄今爲止所嘗試的內容。 – Taosique 2014-09-24 07:23:32