【问题标题】:Insert the date into 2 tables将日期插入 2 个表格
【发布时间】:2013-05-06 10:44:43
【问题描述】:

我有 2 个表,如 Item 和 Image,第一个表 tbl_Item 有 2 个字段,即项目代码、项目名称,第二个表 tbl_Image 有 2 个字段,如项目代码和项目图像。我有项目代码、项目名称、项目图像和一个按钮等字段。当我单击提交按钮时,这些记录被插入到两个表中。我想将数据插入两个表中怎么可能?任何机构都可以建议我吗?

    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)";

【问题讨论】:

  • 那是真正的代码吗,因为我认为你用列名交换了参数,另外你确定你的表Image不是基于tblItem的视图吗?
  • “当我点击提交按钮时,这些记录会插入到两个表中” - 你确定吗?您是否只在按钮单击时执行一个查询?数据库是否包含任何触发器,或者它确实是 @Habib 所说的视图?这太模糊了,无法解决,请显示更多信息。
  • 谢谢哈比布,是的,它是一个真正的代码,首先我尝试了两个字段,然后我会添加
  • 谢谢CodeCaster,我不知道两张表的确切命令,所以我发布了这张表,我们可以使用上面的命令将数据插入到一张表中
  • 可能有任何代码写入选择图像以将图像插入第二个表!

标签: c# asp.net sql-server


【解决方案1】:

是的,您可以同时插入两个表。检查此代码:

注意:您原来的插入查询有误,我已经修改了。

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();
    }
}

【讨论】:

  • 谢谢 skumar,它对我有用,但在这里你传递静态值,我想如何动态传递值?
【解决方案2】:

如果您想在单个命令执行中插入两条记录,请使用“;”加入查询。

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

【讨论】:

  • SQL 查询本身错误。必须是@"insert into tbl_item (ItemCode,ItemName) values(@itemcode,@itemname)";
  • 是的,我改了 Deniyal Tandel
猜你喜欢
  • 2012-01-01
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
  • 2014-01-28
  • 1970-01-01
  • 2015-10-30
相关资源
最近更新 更多