I have two tables, one for storing person information and one for storing his phone numbers, tbl -persons is connected to tbl_phones table using forgin key.
I have one form to insert into two tables and this is the function
private void save()
{
SqlCommand cmd = new SqlCommand("insert into tbl_persons (name,address,fax,mobile,email,website) values (@name,@address,@fax,@mobile,@email,@website)" + "Select Scope_Identity()", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", T_name.Text.Trim());
cmd.Parameters.AddWithValue("@address", T_address.Text.Trim());
cmd.Parameters.AddWithValue("@fax", T_fax.Text.Trim());
cmd.Parameters.AddWithValue("@mobile", T_mobile.Text.Trim());
cmd.Parameters.AddWithValue("@email", T_mobile.Text.Trim());
cmd.Parameters.AddWithValue("@website", T_mobile.Text.Trim());
int ID = Int32.Parse(cmd.ExecuteScalar().ToString());
SqlCommand cmd2 = new SqlCommand("insert into tbl_phones (phone,person_id) values (@phone,@person)", conn);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.AddWithValue("@phone", T_phone.Text.Trim());
cmd2.Parameters.AddWithValue("@person", ID);
int val = cmd.ExecuteNonQuery();
int val2 = cmd2.ExecuteNonQuery();
if (val > 0)
{
MessageBox.Show("تم إدخال البيانات بنجاح"+ID, "تم", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading);
resetFields();
GetDate();
}
}
but the error is that the person info is inserted twice and the phone number is inserted one one time, what is the error ?
You are executing the command in cmd twice. One is here:
int ID = Int32.Parse(cmd.ExecuteScalar().ToString());
And the other here:
int val = cmd.ExecuteNonQuery();
Both instructions (cmd.ExecuteScalar() and cmd.ExecuteNonQuery()) run the command. Make sure you only have one of them (probably the first one, but you are the owner of your logic, so that's your call).
Looks like you're executing cmd twice.
Once here:
\/
int ID = Int32.Parse(cmd.ExecuteScalar().ToString());
/\
and once here:
\/
int val = cmd.ExecuteNonQuery();
/\
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With