Web表单在数据库中两次上传相同的数据

时间:2013-12-13 12:07:42

标签: c# asp.net

我正在将数据上传到数据库,但是我的表单在数据库中上传了相同的数据两次我没有检查天气是否插入上传或没有工作正常现在单独上传数据我已经检查了如果插入的数据比显示插入的消息数据成功但这是两次上传数据。

这是我的代码:

SqlConnection conn1 = new SqlConnection("Data Source=ZAZIKHAN\\SQLEXPRESS;Initial Catalog=resume;Integrated Security=True");
conn1.Open();

SqlCommand cmd3 = new SqlCommand("insert into Profile(Id,Name,JobTitle,Phone,Email,Address,Website,Facebook,Twitter,GooglePlus,Skype,Picture,WhyMeText) values('"+ID.Text+"','" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + uploadFolderPath + "','" + TextArea1.InnerText + "')", conn1);

cmd3.ExecuteNonQuery();
if (cmd3.ExecuteNonQuery() == 1)
{
        Response.Write("<script LANGUAGE='JavaScript' >alert('information saved Successful')</script>");
        TextBox1.Text = "";
        TextBox2.Text = "";
        TextBox3.Text = "";
        TextBox4.Text = "";
        TextBox5.Text = "";
        TextBox6.Text = "";
        TextBox7.Text = "";
        TextBox8.Text = "";
        TextBox9.Text = "";
        TextBox10.Text = "";
        TextArea1.InnerText = "";
}
else { Response.Write("<script LANGUAGE='JavaScript' >alert('sorry try again')</script>"); }

conn1.Close();

3 个答案:

答案 0 :(得分:9)

因为您执行了SqlCommand两次。

一个是

cmd3.ExecuteNonQuery();

另一个是;

if (cmd3.ExecuteNonQuery() == 1)

来自MSDN;

  

对连接执行 Transact-SQL语句并返回   受影响的行数。

请始终使用parameterized queries。这种字符串连接对SQL Injection攻击开放。

还可以使用using声明来处理您的SqlConnection;

using(SqlConnection conn1 = new SqlConnection("Data Source=ZAZIKHAN\\SQLEXPRESS;Initial Catalog=resume;Integrated Security=True"))
{
    //Write here your command with parameterized way..
    conn1.Open();
    if (cmd3.ExecuteNonQuery() == 1)
    {
      //....
    }
}

答案 1 :(得分:2)

删除第一个cmd3.ExecuteNonQuery();,它会正常工作

答案 2 :(得分:1)

如果你想获得布尔结果,请执行以下操作:

  bool result = Convert.ToBoolean(cmd3.ExecuteNonQuery());
  if(result)
   {
      //Rest of function
   }