2013-05-06 107 views
0

我有兩個表,如Item和Image,第一個表tbl_Item有兩個字段,分別是項目代碼,項目名稱和第二個表。tbl_Image有兩個字段,如項目代碼和項目圖像。我有項目代碼,項目名稱,項目圖像和一個按鈕等字段。當我點擊提交按鈕時,這些記錄被插入到兩個表中。我想將數據插入到兩個表中如何可能?任何機構都可以提示我嗎?將日期插入到兩個表中

cmd.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ToString()); 
    cmd.CommandText = "insert into tbl_item (@itemcode,@itemname) values(ItemCode,ItemName)"; 
    cmd.CommandText = "insert into tbl_image (@itemcode,@itemimage) values(ItemCode,ItemImage)"; 
+2

那是真正的代碼,因爲我覺得你有列名換參數,再加上你確定你的表'Image'是不是基於'tblItem'一個看法? – Habib 2013-05-06 10:46:22

+0

_「當我點擊提交按鈕時,這些記錄被插入到兩個表中」_ - 你確定嗎?你只在按鈕點擊時執行一個查詢嗎?數據庫是否包含任何觸發器,或者確實是@Habib所說的視圖?這太難以解決,請顯示更多信息。 – CodeCaster 2013-05-06 10:48:12

+0

謝謝Habib,是的,它是一個真正的代碼首先我嘗試了兩個領域,然後我將添加 – Vijaya 2013-05-06 10:49:28

回答

1

如果要在單個命令執行中插入兩個記錄,然後用「;」連接查詢。

cmd.CommandText = "insert into tbl_item (@itemcode,@itemname) values(ItemCode,ItemName);insert into tbl_image (@itemcode,@itemimage) values(ItemCode,ItemImage)"; 
+0

謝謝你這麼多Deniyal Tandel它的工作。 – Vijaya 2013-05-06 13:22:13

+0

SQL查詢本身是錯誤的。它必須是@「insert into tbl_item(ItemCode,ItemName)values(@ itemcode,@ itemname)」; – 2013-05-06 15:15:52

+0

雅我改變它Deniyal Tandel – Vijaya 2013-05-07 08:02:11

3

是的,你可以同時插入兩個表。請檢查以下代碼:

說明:您原來的插入查詢是錯誤的,我修改了它。

public void InsertIntoDataBase(int itemCode, string itemName, string itemImage) 
{ 
    string connString = ConfigurationManager.ConnectionStrings[1].ToString(); 
    string query1 = @"insert into tbl_item (ItemCode,ItemName) values(@itemcode,@itemname)"; 
    string query2 = @"insert into tbl_image (ItemCode,ItemImage) values(@itemcode,@itemimage)"; 

    SqlConnection conn = new SqlConnection(connString); 

    try 
    { 
     // Exc]ecute the first query. 
     SqlCommand cmd = new SqlCommand(query1, conn); 
     cmd.Parameters.Add("@itemcode", SqlDbType.Int, 10, "ItemCode").Value = itemCode; // Pass the actual Item code 
     cmd.Parameters.Add("@itemname", SqlDbType.Text, 20, "ItemName").Value = itemName; //Pass the actual Item name 
     cmd.ExecuteNonQuery(); 


     // Exc]ecute the second query. 
     cmd = new SqlCommand(query2, conn); 
     cmd.Parameters.Add("@itemcode", SqlDbType.Int, 10, "ItemCode").Value = itemCode; // Pass the actual Item code 
     cmd.Parameters.Add("@itemimage", SqlDbType.Text, 20, "ItemImage").Value = itemImage; // Pass the actual Item image 
     cmd.ExecuteNonQuery(); 
    } 
    catch (Exception e) 
    { 

    } 
    finally 
    { 
     conn.Close(); 
    } 
} 
+0

謝謝你skumar它工作給我,但在這裏你傳遞靜態值,我想動態地傳遞值? – Vijaya 2013-05-06 12:55:52

+0

@ user2131469:我更新了代碼,進行驗證。 – 2013-05-06 15:14:46