簡體   English   中英

C#插入值外鍵

[英]C# Insert Value Foreign Key

我有2個表,分別是tableCustomerLogin和tableCustomerRegister。 tableCustomerLogin有外鍵,即cust_id

在tableCustomerLogin中,我有tableCustomerLogin

    cust_login_id
    cust_id
    cust_email
    cust_username
    cust_password

對於tableCustomerRegister,

    tableCustomerRegister
    cust_id
    cust_fullname
    cust_username
    cust_email
    cust_password
    cust_mobile_number
    cust_image
    cust_address1
    cust_address2
    cust_city
    cust_postcode
    cust_create_acc_time

客戶注冊時,數據將存儲在tableCustomerRegister中。 如何使其在tableCustomerLogin中注冊?

string sql = @"INSERT INTO tableCustomerRegister VALUES (@cust_fullname, @cust_username, @cust_email, @password, @cust_mobile_phone, @cust_address1, @cust_address2, @cust_image, @cust_city, @cust_state, @cust_postcode, @cust_create_acc_time, @role, @enabled)";

            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@cust_fullname", txtFirstName.Text + " " + txtLastName.Text);
            cmd.Parameters.AddWithValue("@cust_username", txtUsername.Text);
            cmd.Parameters.AddWithValue("@cust_email", txtEmail.Text);
            cmd.Parameters.AddWithValue("@password", passwordhash);
            cmd.Parameters.AddWithValue("@cust_mobile_phone", txtMobilePhone.Text);
            cmd.Parameters.AddWithValue("@cust_address1", txtAddress1.Text);
            cmd.Parameters.AddWithValue("@cust_address2", txtAddress2.Text);
            cmd.Parameters.AddWithValue("@cust_image", txtProfilePicture.Text);
            cmd.Parameters.AddWithValue("@cust_city", ICityString());
            cmd.Parameters.AddWithValue("@cust_state", ddState.SelectedValue.ToString());
            cmd.Parameters.AddWithValue("@cust_postcode", txtPostcode.Text);
            cmd.Parameters.AddWithValue("@cust_create_acc_time", DateTime.Now);
            cmd.Parameters.AddWithValue("@role", "user");
            cmd.Parameters.AddWithValue("@enabled", enabled);
            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                lblStatus.Text = "Status: Data successfully saved.";
            }

好吧,首先您需要更改查詢

string sql = @"INSERT INTO tableCustomerRegister  OUTPUT INSERTED.cust_id VALUES (@cust_fullname, @cust_username, @cust_email, @password, @cust_mobile_phone, @cust_address1, @cust_address2, @cust_image, @cust_city, @cust_state, @cust_postcode, @cust_create_acc_time, @role, @enabled)";
 SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.AddWithValue("@cust_fullname", txtFirstName.Text + " " + txtLastName.Text);
        cmd.Parameters.AddWithValue("@cust_username", txtUsername.Text);
//so on (all your parameters)
var custid  = (int)cmd.ExecuteScalar()

ExecuteScalar返回int,在這種情況下,它將返回cust_id因為您的查詢具有OUTPUT INSERTED.cust_id 現在,您已將插入的cust_id保存在tableCustomerRegister中 現在,您只需要編寫另一個查詢即可使用外鍵cust_id將數據保存到tableCustomerLogin中 像這樣,

string Sql2 = "INSERT INTO tableCustomerLogin (column_names) VALUES (parameters values)";
SqlCommand cmd = new SqlCommand(sq2, conn);
cmd.Parameters.AddWithValue("@cust_id",custid);  //as foreign key
//all other Parameters

您可以首先insert tableCustomerRegister記錄,然后在tableCustomerLogin表中insert另一個數據。 您最好在事務塊中執行此操作。

另一種方法是,您可以將trigger添加到tableCustomerLogin表。

CREATE TRIGGER trg_tableCustReg ON tableCustomerRegister
FOR INSERT
AS   
  /*
   *  if CustLoginID is a identity , no dont need to add  
   */ 
    INSERT INTO tableCustomerLogin 
            (cust_login_id, cust_id, cust_email, cust_username, cust_password)
        Select
            'CustLoginID', 
            cust_id , 
            cust_email, 
            cust_username, 
            user_password
            FROM inserted

go

最好的解決方案可能是遵循DRY原則,“不要重復自己”。

我認為您可以將所有信息存儲在單個表customer_table中,然后僅從該表中使用更簡單的邏輯來檢索必要的數據。

相反,如果您想保留實際的數據結構,只需在以分號分隔第一句之后添加新的insert語句即可。

如何一次將數據插入多個表

有兩種不同的方式。 您應使用SCOPE_IDENTITY

string sql = @"INSERT INTO tableCustomerRegister VALUES (@cust_fullname, @cust_username, @cust_email, @password, @cust_mobile_phone, @cust_address1, @cust_address2, @cust_image, @cust_city, @cust_state, @cust_postcode, @cust_create_acc_time, @role, @enabled) SELECT SCOPE_IDENTITY()";

SCOPE_IDENTITY返回插入到同一作用域的標識列中的最后一個標識值

var newId= cmd.ExecuteScaler();

newId為您創建了新的主鍵ID cust_id

您具有此ID(cust_id),並且可以在“登錄”表中注冊。

INSERT INTO  tableCustomerLogin (cust_login_id,**cust_id**,cust_email,cust_username,cust_password)


cust_id = newId 

如果在tableCustomerRegister表中自動創建了Cust_id,則可以將相同的id保存在tableCustomerLogin表中(cust_id)。 那么只有您的外鍵關系起作用。

     try
                    {
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        SqlCommand get_custid_cmd = new SqlCommand("select @@identity", conn);
                        int cust_id = Convert.ToInt32(get_custid_cmd.ExecuteScalar());
                        string sql_insert = @"INSERT INTO tableCustomerLogin VALUES (@cust_id, @cust_username, @cust_email, @password)";

                SqlCommand cmd_insert = new SqlCommand(sql_insert, conn);
                cmd_insert.Parameters.AddWithValue("@cust_id",cust_id);
                cmd_insert.Parameters.AddWithValue("@cust_username", txtUsername.Text);
                cmd_insert.Parameters.AddWithValue("@cust_email", txtEmail.Text);
                cmd_insert.Parameters.AddWithValue("@password", passwordhash);
                cmd_insert.ExecuteNonQuery();
                            lblStatus.Text = "Status: Data successfully saved.";

                    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM