2015-04-16 106 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(); 
    } 
} 

注意:代码直接写在这里,可能会发现一些错误。

相关问题