2

SqlDataAdapter在填充后创建一个Dataset. 我的问题是插入后我想获取IDENTITY主列的值。例如,在插入后给定 buttonedit1 编辑值是Id(这是我的主列),我想在 ButtonEdit1 文本中获取标识值。

除非使用 SQL 命令,否则我可以这样做吗Select @IDentity

谢谢。

public void Form1_Load(object sender,EventArgs e)
{
   try
   {
      SqlConnection con = new SqlConnection(@"ConString");

      con.Open();

      adap = new SqlDataAdapter("select Id,Caption from SKMenu where ID=-1",con);
      adap.Fill(ds, "Table");

      bs.DataSource = ds.Tables["Table"];

      buttonEdit1.DataBindings.Add("Text", bs, "Id");
      buttonEdit2.DataBindings.Add("Text", bs, "Caption");

      bs.AddNew();
}

private void button1_Click(object sender, EventArgs e)
{
   SqlCommandBuilder cv = new SqlCommandBuilder(adap);            

   bs.EndEdit();

   adap.Update(ds.Tables["Table"]);
}
4

2 回答 2

3
    public static bool CreateEntity(object entity, out long id)
    {
        bool created = false;
        long newid = -1;

        DataTable table = new DataTable();

        using (SqlConnection conn = new SqlConnection(Provider.Connection()))
        {
            string sqlcreate = "select * from {0} where id = -1;";
            conn.Open();
            using (SqlDataAdapter da = new SqlDataAdapter(String.Format(sqlcreate, entity.GetType().UnderlyingSystemType.Name), conn))
            {

                using (SqlCommandBuilder build = new SqlCommandBuilder(da))
                {
                    using (DataSet ds = new DataSet())
                    {
                        da.Fill(ds);

                        DataRow dr = ds.Tables[0].NewRow();

                        ClassProperties.Update(entity, dr);
                        da.InsertCommand = build.GetInsertCommand();
                        da.InsertCommand.CommandText += ";SELECT SCOPE_IDENTITY()";
                        da.InsertCommand.Parameters.Clear();
                        for (int i = 1; i < dr.ItemArray.Length; i++)
                        {
                            da.InsertCommand.Parameters.AddWithValue("@p" + i, dr.ItemArray[i]);
                        }

                        var result = da.InsertCommand.ExecuteScalar();
                        if (result != null)
                        {
                            created = true;
                            newid = Convert.ToInt64(result);
                        }
                    }
                }
            }
        }

        id = newid;
        return created;
    }
于 2014-03-07T14:33:32.690 回答
1

如果您将 Adpater 上 InsertCommand 上的命令更改为此您应该没问题

INSERT INTO  SKMenu  ( Caption ) VALUES ( @Caption);
SELECT Id, Caption FROM SKMenu WHERE id = SCOPE_IDENITY();

您也可以使用 OUTPUT 子句

更新命令应该类似于

UPDATE  SKMenu  SET Caption = @Caption WHERE ID = @id;

IIRC 数据集足够聪明,知道何时使用更新或插入,只要您ds.AcceptChanges()adap.Update().

于 2011-06-28T21:11:27.490 回答