Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert into two sql related tables?

Tags:

c#

sql

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 ?

like image 632
amer Avatar asked Jan 27 '26 05:01

amer


2 Answers

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).

like image 192
Adriano Carneiro Avatar answered Jan 28 '26 17:01

Adriano Carneiro


Looks like you're executing cmd twice.

Once here:

                      \/
int ID = Int32.Parse(cmd.ExecuteScalar().ToString());
                      /\

and once here:

           \/
int val = cmd.ExecuteNonQuery();
           /\
like image 31
Joe Stefanelli Avatar answered Jan 28 '26 18:01

Joe Stefanelli