简体   繁体   中英

How not add new data into database that has similar id with data in database?

So I am making a Project a in Windows Forms and what I have to do is to get data from Excel and display it in Datagridview. I am Uploading data on Sql Server and than I am sending it in DVG.Every Time I Upload data on Server I have to add new data to old data but I does not have datas in database with similar id. I have Code to add new data in sql Server but I donn't know how not to add new data, that have a similar id with data in sql. Has anyone idea how t do that ? Here is my Code:

SqlBulkCopy oSqlBulk = null;

            string excelFilePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            excelFilePath = Path.Combine(excelFilePath, label1.Text);
            OleDbConnection excelConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + ";Extended Properties=Excel 12.0;");

            try
            {
                excelConn.Open();
                OleDbCommand excelComm = new OleDbCommand("SELECT *FROM [Sheet1$]", excelConn);

                OleDbDataReader excelreader = excelComm.ExecuteReader();

                using(SqlConnection con = new SqlConnection("Data Source=DESKTOP-OETHK6U\\SQLEXPRESS;Initial Catalog=Intel_DB;Integrated Security=True"))
                {
                    con.Open();
                    oSqlBulk = new SqlBulkCopy(con);
                    oSqlBulk.DestinationTableName = "Intel_Data";
                    oSqlBulk.WriteToServer(excelreader);
                }
                label2.Text = "Data has been added into database";
            }
            catch(Exception ex)
            {
                label2.Text = "Data has not been added into database";
                MessageBox.Show(ex.Message);
            }
            finally
            {
                oSqlBulk.Close();
                oSqlBulk = null;
                excelConn.Close();
                excelConn = null;
            }

Try this

if (not exists(select * from table where ID= @id))
insert into table(fields) values (values)

or you can set unique constraint in ID so if user add same id it will throw error where you have handle it..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM