是的,你可以同時插入兩個表。請檢查以下代碼:
說明:您原來的插入查詢是錯誤的,我修改了它。
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();
}
}
那是真正的代碼,因爲我覺得你有列名換參數,再加上你確定你的表'Image'是不是基於'tblItem'一個看法? – Habib 2013-05-06 10:46:22
_「當我點擊提交按鈕時,這些記錄被插入到兩個表中」_ - 你確定嗎?你只在按鈕點擊時執行一個查詢嗎?數據庫是否包含任何觸發器,或者確實是@Habib所說的視圖?這太難以解決,請顯示更多信息。 – CodeCaster 2013-05-06 10:48:12
謝謝Habib,是的,它是一個真正的代碼首先我嘗試了兩個領域,然後我將添加 – Vijaya 2013-05-06 10:49:28