消除重复记录插入数据库

时间:2016-07-01 11:04:28

标签: c# asp.net sql-server

以下是我将gridview数据插入数据库的代码。但是,使用这个我想检查并限制插入数据库,其中记录具有相同的名称,位置,教育和工资。如果所有这些都是相同的并且数据库中已经存在它们,则不应插入它们。如果任何一列不同,则应插入它们。

protected void btn_insert_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow g1 in GridView1.Rows)
            {
                SqlConnection con = new SqlConnection(connStr);
                cmd = new SqlCommand("insert command", con);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            UploadStatusLabel.Text = "Records Inserted Successfully";
        }

2 个答案:

答案 0 :(得分:0)

我认为当你有其他选择时,在for循环中访问数据库是一个非常糟糕的主意。我不会在下面的示例中解决这个问题。

您的代码可能受SQL注入,您需要使用参数来传递您的值。如果某人使用";DROP TABLE OpenOfficetext;"填充输入并且他们具有DROP权限,那么如果您只是连接字符串将会出现问题。

为避免重复,您可以先检查是否存在类似的记录。

foreach (GridViewRow g1 in GridView1.Rows)
{
    string insertCommand = "insert into OpenOfficetext(Name, Location, Education, Salary) values(@p1, @p2, @p3, @p4)";
    string selectCommand = "SELECT COUNT(*) FROM OpenOfficetext WHERE Name = @p1 AND Location = @p2 AND Education = @p3 AND Salary = @p4";

    SqlConnection con = new SqlConnection(connStr);
    SqlCommand cmd = new SqlCommand(selectCommand, con);

    con.Open();
    cmd.Parameters.AddWithValue("@p1", g1.Cells[0].Text);
    cmd.Parameters.AddWithValue("@p2", g1.Cells[1].Text);
    cmd.Parameters.AddWithValue("@p3", g1.Cells[2].Text);
    cmd.Parameters.AddWithValue("@p4", g1.Cells[3].Text);

    if (Convert.ToInt32(cmd.ExecuteScalar()) == 0)
    {
        cmd.CommandText = insertCommand;
        cmd.ExecuteNonQuery();
    }

    con.Close();
}

答案 1 :(得分:-2)

请使用以下代码

if not exist (select * from OpenOfficetext where Name='" + g1.Cells[0].Text + "' and Location='" + g1.Cells[1].Text + "' and  Education = '" + g1.Cells[2].Text + "' and Salary = '" + g1.Cells[3].Text + "' )

Begin
SqlConnection con = new SqlConnection(connStr);
 cmd = new SqlCommand("insert into OpenOfficetext(Name,Location,Education,Salary) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);

  con.Open();
  cmd.ExecuteNonQuery();
  con.Close();

End
相关问题