2015-02-11 65 views
-4

對於我的培訓生,我必須做一些SQL請求。如何在一次執行多個請求

我嘗試這transfert從csv文件數據到SQL服務器數據庫

string str = Path.GetFullPath("."); 
    String conn = @"Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=""Text;HDR=No;FMT=Delimited"";Data Source="+str+""; 
    string strCnx = "Database=" + ConfigurationManager.AppSettings["base"] + ";data source=" + ConfigurationManager.AppSettings["servername"] + ";User Id=" + ConfigurationManager.AppSettings["user"] + ";Password=" + ConfigurationManager.AppSettings["password"] + ";Connect Timeout=10"; 
    // Open a sourceConnection to the AdventureWorks database. 
    //using (OleDbConnection sourceConnection = new OleDbConnection(strCnx)) 
    { 
     //sourceConnection.Open(); 

     // Get data from the source table as a SqlDataReader. 
     OleDbConnection cn = new OleDbConnection(conn); 
     OleDbCommand commandSourceData = new OleDbCommand("SELECT * FROM [" + ConfigurationManager.AppSettings["csvname"] + "]", cn); 
     OleDbDataAdapter da = new OleDbDataAdapter(commandSourceData); 
     cn.Open(); 
     OleDbDataReader reader = commandSourceData.ExecuteReader(); 

     // Open the destination connection. In the real world you would 
     // not use SqlBulkCopy to move data from one table to the other 
     // in the same database. This is for demonstration purposes only. 
     using (SqlConnection destinationConnection = new SqlConnection(strCnx)) 
     { 
      destinationConnection.Open(); 

      // Set up the bulk copy object. 
      // Note that the column positions in the source 
      // data reader match the column positions in 
      // the destination table so there is no need to 
      // map columns. 
      using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection)) 
      { 
       bulkCopy.DestinationTableName = "GudsisUser"; 

       bulkCopy.WriteToServer(reader); 
      } 
      Console.WriteLine("Press Enter to finish."); 
      Console.ReadLine(); 
     } 

但應用程序返回一個錯誤消息:無法解析字符串值轉換爲NCHAR值

我不知道如果我PROGRAMM正確與否

+0

你說什麼樣的「請求」,你是否試圖逐一插入記錄? – Habib 2015-02-11 15:40:57

+0

您可以對DataSet進行所有數據修改,並隱藏更新或插入的實際過程,但最終它將始終是針對您的數據庫執行的INSERT或UPDATE語句。 – Filburt 2015-02-11 15:43:00

+0

發佈一些代碼。你的問題真的很模糊,很難理解,沒有任何代碼 – Paolo 2015-02-11 15:43:34

回答

1

我猜你在找什麼東西叫BULK INSERT(做一個DB請求中的一切嗎?)

如果是這樣,看看答案here

+0

此外,這裏有一個非常好的通用解決方案:http://blog.developers.ba/bulk-insert-generic-list-sql-server-minimum-lines-code/ – quetzy 2015-02-11 15:55:05

+0

我需要「存儲」我的請求和他的參數來執行循環中的所有請求。 – 2015-02-11 16:02:27

+0

對於您想要執行的操作,無法在循環中每次創建和執行SqlCommand。在循環前面創建SqlCommand,只將值加載到循環內的表中,並在循環後僅執行一次批量插入(包含所有數據)。 對於實現的想法,請檢查兩個鏈接。 – quetzy 2015-02-11 16:11:40