C# 控制檯程序-將數據庫查詢結果導出CSV文檔

因項目需要從IBM DB2進行數據獲取,並上傳至指定FTP位置,非常基礎的一個程序,留存備用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Data.OleDb;

namespace YieldRechargeToH2
{
    class Program
    {
        static void Main(string[] args)
        {
            // 定義數據庫鏈接字符串,若Provider報錯,去掉也行
            string strConn = "Provider=IBMDADB2;Database=IBMDADB2;HOSTNAME= HostIPAddr ;PROTOCOL=TCPIP;PORT= PortID;uid=UserName;pwd=PWD;";
            // SQL代碼
            string sql = @"select * from tableName;";
            // 定義CSV文檔存儲路徑,可先映射FTP盤至本地
            string path = "W:\\";
            // 定義CSV文檔文件名
            string fileName = "Data-" + DateTime.Now.Date.ToString("yyyyMMdd") + "01.csv";
            // SaveCSV
            string exportFileName = string.Format(path + fileName);

            OleDbConnection conn = new OleDbConnection(strConn); // 實例化Connection
            try
            {
                conn.Open(); // 打開鏈接
                Console.WriteLine("數據庫鏈接成功!");
                OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);  // 實例化DataAdapter對象
                DataSet ds = new DataSet();
                da.Fill(ds);
                conn.Close();
                using (StreamWriter streamWriter = new StreamWriter(exportFileName, false, Encoding.Default))
                {
                    if (ds.Tables[0].Rows == null || ds.Tables[0].Rows.Count == 0)   //確保DataTable中有數據
                        return;
                    string strBufferLine = "";
                    //寫入列頭
                    foreach (System.Data.DataColumn col in ds.Tables[0].Columns)
                    strBufferLine += col.ColumnName + ",";
                    strBufferLine = strBufferLine.Substring(0, strBufferLine.Length - 1);
                    streamWriter.WriteLine(strBufferLine);
                    //寫入記錄
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        strBufferLine = "";
                        for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                        {
                            if (j > 0)
                            strBufferLine += ",";
                            strBufferLine += ds.Tables[0].Rows[i][j].ToString().Replace(",", "");   //因爲CSV文件以逗號分割,在這裏替換爲空
                        }
                        streamWriter.WriteLine(strBufferLine);
                    }
                    streamWriter.Flush();
                    streamWriter.Close();

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            conn.Close();
        }
    }
}



for循環中也可用DataSet代替;
以下附上上傳FTP的代碼

#region 上傳到FTP server

            string strUnicomFtpUrl = "ftp://X.X.X.X/"; // 取得FTP的ip
            string strUnicomFtpAccount = "UserName"; // 取得FTP的User
            string strUnicomFtpPassword = "PWD"; // 取得FTP的Pwd
            //確認FTP上有對應資料夾 
            FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(strUnicomFtpUrl + string.Format("{0}.csv", ExportFileName));
            uploadRequest.Credentials = new NetworkCredential(strUnicomFtpAccount, strUnicomFtpPassword);
            uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;

            FileStream fileStream = null;
            Stream uploadStream = null;
            try
            {
                FileInfo fileInfo = new FileInfo(path);
                fileStream = fileInfo.OpenRead();

                int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];

                uploadStream = uploadRequest.GetRequestStream();

                int contentLength = fileStream.Read(buffer, 0, bufferLength);

                while (contentLength != 0)
                {
                    uploadStream.Write(buffer, 0, contentLength);
                    contentLength = fileStream.Read(buffer, 0, bufferLength);
                }

                uploadStream.Close();
                fileStream.Close();

                uploadRequest = null;
            }
            catch (Exception ex)
            {
                manage.Log.WriteError(string.Format("{0},{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                if (uploadStream != null)
                {
                    uploadStream.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                }
                if (uploadRequest != null)
                {
                    uploadRequest = null;
                }
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            #endregion
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章