2017-05-04 83 views
0

我已經實現了一個web和Windows應用程序,該應用程序擊中包含csv文件路徑的URL。我使用WebClient來下載文件,然後從.csv讀取數據並寫入SQL Server表。從URL導入CSV並存儲到SQL Server表中而不下載文件

有沒有辦法做到這一點,而無需下載/保存.csv並使用存儲過程將URL的響應.csv寫入SQL Server表中?

下面是我工作的C#代碼的片段。

URL_VALUE = "http://test.url.com/table.csv?test.csv"; 
string csvPath = "~C:\\SaveFile\\test.csv"; 

WebClient client = new WebClient(); 
client.DownloadFile(@URL_VALUE, csvPath); 

writeToSQL(csvPath, Symbol); 

// Code snippet for SQL Write operation 
public void writeToSQL(string url, string filepath) 
{ 
    using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(connection)) 
    { 
     // Set the database table name 
     sqlBulkCopy.DestinationTableName = "dbo.csv_PopulateData"; 

     sqlBulkCopy.ColumnMappings.Add("Col1", "Val1"); 
     sqlBulkCopy.ColumnMappings.Add("Col2", "Val2"); 
     sqlBulkCopy.ColumnMappings.Add("Col3", "Val3"); 

     sqlBulkCopy.WriteToServer(table); 
    } 
} 
+1

無論這是否可能,從安全的角度來看,我總是避免數據庫直接與互聯網通信。 –

+1

感謝您的領導!我將嘗試編寫一個RESTFull API,它將以JSON/XML格式獲取httpResponse,然後寫入SQL Server表。 –

+0

使用'HttpWebRequest'和'HttpWebResponse'方法我能夠從URL上的'.csv'文件中提取數據並寫入SQL Server表。 –

回答

0

使用HttpWebRequestHttpWebResponse方法,我能夠從目前.csv文件拉動URL數據並寫入到一個SQL Server表。

public void getFileData() 
    { 
     try 
     { 

      Uri CSVUri = new Uri("URL"); 
      WebRequest = (HttpWebRequest)HttpWebRequest.Create(CSVUri); 
      webResponse = (HttpWebResponse)WebRequest.GetResponse(); 
      if (webResponse.StatusCode == HttpStatusCode.OK) 
      { 
       System.IO.StreamReader strReader = new System.IO.StreamReader(WebRequest.GetResponse().GetResponseStream()); 
       //create datatable with column names (Headers) 
       Createtable(strReader.ReadLine()); 
       String SingleLine; 
       while ((SingleLine = strReader.ReadLine()) != null) 
       { 
        AddRowtable(SingleLine); //Add data into dataset 
       } 

       GridView1.DataSource = datatable1; 

       using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) 
       { 
        foreach (DataColumn c in datatable1.Columns) 
        bulkCopy.ColumnMappings.Add(c.ColumnName, c.ColumnName); 

        bulkCopy.DestinationTableName = "dbo.tableName"; 
        try 
        { 
         bulkCopy.WriteToServer(datatable1); 
        } 
        catch (Exception ex) 
        { 
         string display = "Exception Occured"; 
         ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true); 
        } 
       } 

       if (strReader != null) strReader.Close(); 
      } 
     } 
     catch (System.Net.WebException ex) 
     { 
      string display = "Exception Occured"; 
      ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true); 
     } 
    } 
相關問題