Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web form upload same data twice in database

Tags:

c#

asp.net

I am uploading data to databases but my form upload the same data twice in databases first I was uploading data without checking weather is inserted or not it was working fine it was uploading the data single time now I have put the checked that if data inserted than show the message data inserted successful but this is uploading data twice.

Here is my code:

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();
like image 505
Vicky Avatar asked Dec 13 '13 12:12

Vicky


3 Answers

Because you execute your SqlCommand twice.

One is with

cmd3.ExecuteNonQuery();

And the other one is with;

if (cmd3.ExecuteNonQuery() == 1)

From MSDN;

Executes a Transact-SQL statement against the connection and returns the number of rows affected.

And please always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

Also use using statement to dispose your SqlConnection like;

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)
    {
      //....
    }
}
like image 83
Soner Gönül Avatar answered Oct 23 '22 21:10

Soner Gönül


Remove the first cmd3.ExecuteNonQuery(); and it will work fine

like image 39
Aitazaz Khan Avatar answered Oct 23 '22 19:10

Aitazaz Khan


if you want to get boolean result, perfom this one :

  bool result = Convert.ToBoolean(cmd3.ExecuteNonQuery());
  if(result)
   {
      //Rest of function
   }
like image 1
Sohail Avatar answered Oct 23 '22 21:10

Sohail