應用環境:visual studio 2010開發工具,Database為Sql2008以上版本

最近在生產環境中需要開發一款應用程式,上傳電子檔(.csv)資料至Database

最初方案:

以txt方式打開Csv檔案,逐行進行數據上傳處理,代碼見下文。因為需要上傳N台機器產生的檔案,每天數據量非常龐大,並且在上傳時要進行篩選去重,并保留最新的(以測試時間為準)測試記錄,導致以上方案在執行時,當天的資料無法在當天上傳完成,嚴重影響第二天的資料匯總和報表的生成。

改善方案:

因為資料太多太慢被老闆不知道K了多少次。本來想要使用多線程解決,但是考慮到線程間的安全問題,最終還是放棄額。後來思考為什麼不能把整個Csv檔案用放入Table中進行上傳,減少Database的訪問次數,并降低佔用網絡帶寬。

話不多少,先上改善前後的效果圖相差竟然有12秒之多.效率提升43倍之多。

詳細代碼如下:

獲取檔案并逐行讀取資料代碼

private void Readlog()

{

state = false;

foreach (string a in Directory.GetFiles(logfile, "*.csv"))

{

if (GetDataSet.FileCopy(a, logbak + "\\" + a.Substring(a.LastIndexOf("\\") + 1)) == true)

{

string[] read = File.ReadAllLines(a, Encoding.GetEncoding("GB18030"));

for (int i = 1; i < read.Length; i++)

{

if (DataSave(a.Substring(a.LastIndexOf("\\") + 1), read[i].ToString()) == false)

{

ErrorWrite(a.Substring(a.LastIndexOf("\\") + 1) + ":LINE(" + i + ")Write Error");

continue;

}

}

GetDataSet.DeleteFile(a);

}

}

}

上傳資料代碼

private bool DataSave(string a, string sr)

{

try

{

f = false;

SqlConnection con = new SqlConnection();

SqlCommand com = new SqlCommand();

string sql;

con.ConnectionString = "#####";

//ArrayList Panel = new ArrayList();

string[] Panel;

Panel = sr.ToString().Split(',');

com.CommandType = CommandType.Text;

sql = "Insert Avi_Data " +

"([CreateMachine No],[Machie Model],[Model no],[Panel Barcode],[MCH],[Board ID],[Pin NO],[Bad board result],[Pitch FINGER]" +

",[Pitch FINGER(Spec)],[Width FINGER],[Width FINGER (Spec)],[FINGER to Board EDGE SMALL],[FINGER to Board EDGE SMALL(Spec)],[FINGER to Board EDGE LARGE],[FINGER to Board EDGE LARGE(Spec)]" +

",[PCB Width_Finger Area],[PCB Width_Finger Airea (Spec)],[CreateDatetime],[FileName]) values(";

for (int i = 0; i < Panel.Length; i++)

{

sql = sql + "'" + Strings.StrConv(Panel[i].ToString().Trim(), VbStrConv.TraditionalChinese, 0) + "',";

}

sql = sql + "Getdate(),'" + a + "')";

com.CommandText = sql;

com.Connection = con;

con.Open();

com.ExecuteNonQuery();

con.Close();

AddItem(Panel[3].ToString() + ":" + Panel[5].ToString()+"測試資料已上傳!");

return true;

}

catch(Exception ex)

{

ErrorWrite(ex.ToString());

return false;

}

}

改善后方案實施步驟:

1、 在DataBase中創建table變量。

CREATE TYPE [dbo].[MultiRowsInsert] AS TABLE

2、 創建對應的數據保存的存儲過程。

CREATE PROCEDURE [dbo].[InsertMultiRow]

@DataTable dbo.MultiRowsInsert readonly

as

declare @ID int,@MaxID int

set @ID=1

set @MaxID=(Select max(ID) from @DataTable)

while @ID<=@MaxID

begin

insert Avi_Data

select[CreateMachine No],[Machie Model],[Model no],[Panel Barcode],[MCH],[Board ID],[Pin NO],[Bad board result]

,[Pitch FINGER],[Pitch FINGER(Spec)],[Width FINGER],[Width FINGER (Spec)],[FINGER to Board EDGE SMALL]

,[FINGER to Board EDGE SMALL(Spec)],[FINGER to Board EDGE LARGE],[FINGER to Board EDGE LARGE(Spec)]

,[PCB Width_Finger Area],[PCB Width_Finger Airea (Spec)],GETDATE(),[FileName]

from @DataTable

where ID=@ID

set @ID=@ID+1

end

3、 修改程式代碼。

以下為讀取Csv檔案代碼

private void Readlog()

{

state = false;

foreach (string a in Directory.GetFiles(logfile, "*.csv"))

{

if (GetDataSet.FileCopy(a, logbak + "\\" + a.Substring(a.LastIndexOf("\\") + 1)) == true)

{

string[] read = File.ReadAllLines(a, Encoding.GetEncoding("GB18030"));

DataTable TableInsert = new DataTable();

TableInsert.Columns.Add("ID", typeof(int));

TableInsert.Columns.Add("CreateMachine No", typeof(string));

TableInsert.Columns.Add("Machie Model", typeof(string));

TableInsert.Columns.Add("Model no", typeof(string));

TableInsert.Columns.Add("Panel Barcode", typeof(string));

TableInsert.Columns.Add("MCH", typeof(string));

TableInsert.Columns.Add("Board ID", typeof(string));

TableInsert.Columns.Add("Pin NO", typeof(string));

TableInsert.Columns.Add("Bad board result", typeof(string));

TableInsert.Columns.Add("Pitch FINGER", typeof(string));

TableInsert.Columns.Add("Pitch FINGER(Spec)", typeof(string));

TableInsert.Columns.Add("Width FINGER", typeof(string));

TableInsert.Columns.Add("Width FINGER (Spec)", typeof(string));

TableInsert.Columns.Add("FINGER to Board EDGE SMALL", typeof(string));

TableInsert.Columns.Add("FINGER to Board EDGE SMALL(Spec)", typeof(string));

TableInsert.Columns.Add("FINGER to Board EDGE LARGE", typeof(string));

TableInsert.Columns.Add("FINGER to Board EDGE LARGE(Spec)", typeof(string));

TableInsert.Columns.Add("PCB Width_Finger Area", typeof(string));

TableInsert.Columns.Add("PCB Width_Finger Airea (Spec)", typeof(string));

TableInsert.Columns.Add("FileName", typeof(string));

for (int i = 1; i < read.Length; i++)

{

string[] ReadCloumn;

int c=1;

ReadCloumn=read[i].Split(',');

DataRow dr = TableInsert.NewRow();

dr[0] = i;

while (c <= ReadCloumn.Length)

{

dr[c] = ReadCloumn[c-1].Trim();

c++;

}

dr[c] = a.Substring(a.LastIndexOf("\\") + 1);

TableInsert.Rows.Add(dr);

}

if (SaveData(TableInsert) == false)

{

int sn = a.Split('_').Length - 2;

ErrorWrite(a.Split('_')[sn] + ":Write Error");

continue;

}

else

{

int sn=a.Split('_').Length-2;

AddItem( a.Split('_')[sn]+ "測試資料已上傳!");

GetDataSet.DeleteFile(a);

}

}

}

}

數據保存代碼

private bool SaveData(DataTable dt)

{

try

{

SqlConnection con = new SqlConnection();

SqlCommand com = new SqlCommand();

con.ConnectionString = "######";

SqlParameter[] paras = new SqlParameter[]

{

new SqlParameter("@DataTable",dt)

};

string msg= GetDataSet.RunSqlProdurce("InsertMultiRow", paras, con);

if (msg == "ok")

return true;

else

{

return false;

}

}

catch (Exception ex)

{

return false;

}

}

以上為完整代碼,如有更好的方案,還請各方大神不吝賜教……

.net批量上傳Csv檔資料應用程序開發總結的更多相关文章

  1. 將UNITY作品上傳到Facebook App!

    前言 大家好,今天要來介紹如何用UNITY 將製作好的遊戲上傳到Facebook,也就是Facebook App.近期Facebook與Unity合作而推出了新的插件,利用插件可上傳分數.邀請好友.P ...

  2. Active Record: 資料庫遷移(Migration) (转)

    Active Record: 資料庫遷移(Migration) Programming today is a race between software engineers striving to b ...

  3. Delphi APP 開發入門(八)SQLite資料庫

    Delphi APP 開發入門(八)SQLite資料庫 分享: Share on facebookShare on twitterShare on google_plusone_share   閲讀次 ...

  4. [Xamarin] 開啟另外一個Activity 並且帶資料 (转帖)

    每隻App是透過許多畫面所組成的,當然可能主畫面之外,都會有許多其他的頁面 再Android 設計中畫面會有配合的Activity 當然在這之前,最好事先了解一下,Android 關於生命週期的規劃 ...

  5. [转]SQL Server 安全性概論與無法刪除資料庫使用者的解決辦法

    經常有人來問我特定 SQL Server 資料庫裡的使用者無法刪除的問題,這問題其實跟 SQL Server 的安全性架構有很大關係,解決這個問題當然還是瞭解觀念的重要性大於知道如何解決問題.除了講解 ...

  6. 如何將 MySQL 資料庫轉移到 Microsoft SQL Server 與 Azure SQL Database

    MySQL 是相當常用之資料庫伺服器,而微軟雲端服務 Microsoft Azure 上 Azure SQL Database 是一個功能強大且經濟實惠的選擇,透過本篇文章,使用 SQL Server ...

  7. jQuery無刷新上傳之uploadify簡單試用

    先簡單的侃兩句:貌似已經有兩個月的時間沒有寫過文章了,不過仍會像以前那样每天至少有一至兩個小時是泡在园子裏看各位大神的文章.前些天在研究“ajax無刷新上傳”方面的一些插件,用SWFUpload實現了 ...

  8. C++ 檔案、資料夾、路徑處理函式庫:boost::filesystem

    原帖:https://tokyo.zxproxy.com/browse.php?u=uG7kXsFlW1ZmaxKEvCzu8HrCJ0bXIAddA1s5dtIUZ%2FYzM1u9JI7jjKLT ...

  9. [ASP.NET] 如何利用Javascript分割檔案上傳至後端合併

    最近研究了一下如何利用javascript進行檔案分割上傳並且透過後端.特地記錄一下相關的用法 先寫限制跟本篇的一些陷阱 1.就是瀏覽器的支援了 因為本篇有用到blob跟webworker 在ie中需 ...

随机推荐

  1. http学习笔记(一)

    写在前面: 第一次想写系列文章,学习了一些web知识后,发现自己还有很大的不足,但又不知道该学习些什么来完善自己的知识体系,偶然在网上看到了一篇介绍http的文章,觉得对自己有一些帮助,于是想要开始学 ...

  2. 让C#轻松实现读写锁分离--封装ReaderWriterLockSlim

    ReaderWriterLockSlim 类 表示用于管理资源访问的锁定状态,可实现多线程读取或进行独占式写入访问. 使用 ReaderWriterLockSlim 来保护由多个线程读取但每次只采用一 ...

  3. easy-ui 小白进阶史(一):加载数据,easy-ui显示

    作为一个没上过大学,没经过正规培训的96年的小白来说,找工作就没报特别大的希望,大不了找不到在回炉重造,继续学... 终于在海投了200份的简历之后...终于找到了...面试也挺简单的,,,第二天就去 ...

  4. [Linux]Linux下安装和配置solr/tomcat/IK分词器 详细实例二.

    为了更好的排版, 所以将IK分词器的安装重启了一篇博文,  大家可以接上solr的安装一同查看.[Linux]Linux下安装和配置solr/tomcat/IK分词器 详细实例一: http://ww ...

  5. Java六大问题你都懂了吗?

    这些问题对于认真学习java的人都要必知的,当然如果你只是初学者就没必要那么严格了,那如果你认为自己已经超越初学者了,却不很懂这些问题,请将你自己重归初学者行列. 一.到底要怎么样初始化! 本问题讨论 ...

  6. GridView和DATAGRID前后台查询用法的比较

    Grideview前台: <DIV class="mainDiv" id="GridWidth"> <ASP:GridView id=&quo ...

  7. js 判断字符串是否包含另外一个字符串

    示例代码: <script type="text/javascript"> var str = "测试一个字符串(ehtrzes)是否包含另外一个字符串&qu ...

  8. 快速入门系列--WCF--05事务

    最近开始WCF相关知识的学习,虽然实际工作中使用公司自己的一套SOA系统,但微软的一套服务架构还是具有很大的参考意义.除了WCF的一些基础使用,相对比较复杂的内容有分布式的事务和通信的安全等,不过基本 ...

  9. KendoUI系列:AutoComplete

    1.基本使用 <link href="@Url.Content("~/C ontent/kendo/2014.1.318/kendo.common.min.css" ...

  10. Android入门(十五)通知

    原文链接:http://www.orlion.ga/663/ 1.通知的基本用法 创建通知的步骤,首先需要一个NotificationManager来对通知进行管理,可以调用Context的getSy ...