如何在MVC中插入记录之前检查数据库中是否存在任何特定记录?

时间:2015-04-16 04:45:18

标签: sql-server asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我使用以下代码将数据从excel导出到Sql server数据库。这段代码发生了什么,它将完整的数据导入数据库。

[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");
    }

如何检查数据库中是否已存在任何特定记录。如果没有,则将记录插入数据库,否则不应该。

提前致谢!

1 个答案:

答案 0 :(得分:0)

由于您的目标是SQL Server,因此您可以利用此优势。 我要做的是将excel中的数据读入DataTable(而不是使用DataReader,您可以使用DataAdapter),将该DataTable发送到SQL Server中的存储过程,并在那里处理插入。为了将数据表传递给存储过程,首先需要在sql server中创建一个Table-value用户定义类型,如下所示:

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对象并将DataTable添加为参数,如下所示:

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();
    }
}

注意:此处直接编写代码,可能会发现一些错误。