我想知道如何防止重复输入数据库表,以防表已经有该字段的记录。
正如我的表列名:网站是唯一列。而且我上传的 excel 文件可能具有与新数据相同的记录,或者可能具有完全重复的记录,因此基于列名网站,我想防止输入该重复条目,然后输入另一个下一条记录,然后继续。
我希望它清楚,这是我的代码:
protected void btnSend_Click(object sender, EventArgs e)
{
//file upload path
string path = fileuploadExcel.PostedFile.FileName;
//Create connection string to Excel work book
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\File.xlsx';Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
DataTable table = new DataTable();
dReader = cmd.ExecuteReader();
table.Load(dReader);
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "TableName";
sqlBulk.WriteToServer(table);
excelConnection.Close();
int numberOfRowsInserted = table.Rows.Count;// <-- this is what was written.
string message = string.Format("<script>alert({0});</script>", numberOfRowsInserted);
ScriptManager.RegisterStartupScript(this, this.GetType(), "scr", message, false);
}