Click here to Skip to main content
16,020,186 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
private void button2_Click(object sender, EventArgs e)
      {
string path = "E:\\BatchMaster.xls";

          string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";

          OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

          OleDbCommand cmd = new OleDbCommand("Select  *from [Sheet1$]", excelConnection);
          excelConnection.Open();
          OleDbDataReader dReader;
          dReader = cmd.ExecuteReader();
         SqlBulkCopy sqlBulk = new SqlBulkCopy(con);

         sqlBulk.DestinationTableName = "BatchMaster";
          sqlBulk.WriteToServer(dReader);
          excelConnection.Close();
          MessageBox.Show("Successful");


      }




when iam trying to execute this code and click on button2 it shows error Violation of primarykey constraint.

error appeared on sqlBulk.DestinationTableName = "BatchMaster";
sqlBulk.WriteToServer(dReader);

Can any one help me to solve this problem.

Thanks.
Posted

1 solution

There exists a primary key on the table 'BatchMaster' and your excel data conflicts with that primary key constraint. That causes the error. What I advice you is:
1- create a temporary table without any constraint
2- insert excel data into that table.
3- insert data from temporary table to actual table with a special care (checking for constraints, if any error log it, etc)

rule#1: never trust external data.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900