2015-04-16 25 views
-1

我正在使用以下代碼將數據從excel導出到Sql服務器數據庫。這段代碼正在進行的是它將完整的數據導入到數據庫中。如何在MVC中插入記錄之前檢查數據庫中是否存在任何特定記錄?

[HttpPost] 
    public ActionResult Importexcel() 
    {    
     if (Request.Files["FileUpload1"].ContentLength > 0) 
     { 
      string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName); 
      string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName); 
      if (System.IO.File.Exists(path1)) 
       System.IO.File.Delete(path1); 
      Request.Files["FileUpload1"].SaveAs(path1); 
      string sqlConnectionString = @"Data Source=xyz-101\SQLEXPRESS;Database=PracDB;Trusted_Connection=true;Persist Security Info=True"; 
      string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False"; 
      OleDbConnection excelConnection = new OleDbConnection(excelConnectionString); 
      OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection); 
      excelConnection.Open(); 
      OleDbDataReader dReader;    
      dReader = cmd.ExecuteReader(); 
      SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString); 
      sqlBulk.DestinationTableName = "Excel_Table"; 
      sqlBulk.WriteToServer(dReader); 
      excelConnection.Close(); 
     } 
     return RedirectToAction("Index"); 
    } 

如何檢查數據庫中是否存在任何特定的記錄。如果不是,則將該記錄插入到數據庫中,否則它不應該。

在此先感謝!

+0

看到這個答案http://stackoverflow.com/a/8047034/1298308 – Aminul

回答

0

由於您的目標是SQL Server,因此您可以充分利用它。 我會做什麼是從Excel中讀取數據到DataTable中(而不是使用DataReader可以使用DataAdapter),將該DataTable發送到SQL服務器中的存儲過程,並在那裏處理插入。爲了沙數據表,存儲過程,你首先需要在SQL Server中創建一個表值用戶定義類型,像這樣:

CREATE TYPE MyType AS TABLE 
(
    Id int, 
    Name varchar(20), -- use whatever length best fitted to your data 
    Designation varchar(max) -- use whatever length best fitted to your data 
) 

然後,你可以寫一個簡單的存儲過程的參數此類型:

CREATE PROCEDURE InsertDataFromExcel 
( 
    @ExcelData dbo.MyType readonly -- Note: readonly is a required! 
) 
AS 

INSERT INTO MyTable(Id, Name, Designation) 
SELECT a.Id, a.Name, a.Designation 
FROM @ExcelData a LEFT JOIN 
MyTable b ON(a.Id = b.Id) 
WHERE b.Id IS NULL -- this condition with the left join ensures you only select records that has different id values then the records already in your database 

爲了這個參數從C#代碼發送到存儲過程,你將不得不使用一個SqlCommand對象,並新增數據表作爲一個參數,像這樣:

using(SqlConnection Con = new SqlConnection(sqlConnectionString)) 
{ 
    using(SqlCommand InsertCommand = new SqlCommand("InsertDataFromExcel", Con)) 
    { 
     SqlParameter MyParam = new SqlParameter("@ExcelData", SqlDBType.Structured); 
     MyParam.Value = MyDataTable; // this is the data table from the 
     InsertCommand.Parameters.Add(MyParam); 
     Con.Open(); 
     InsertCommand.ExecuteNoQuery(); 
     Con.Close(); 
    } 
} 

注意:代碼直接寫在這裏,可能會發現一些錯誤。

相關問題