如何插入一条记录获取插入后的自动增长ID列的方法.

主要介绍了如何在设定了自动增长ID列后添加一条数据后获取添加的自动增长的ID值方法.

这篇文章我写了一个使用企业库3.0的方法来获取自动增长ID列的方法,代码如下:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

using Microsoft.Practices.EnterpriseLibrary.Data;

using System.Data.Common;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        Database db = DatabaseFactory.CreateDatabase("SQLConnectionString");

        string strSql = @"INSERT INTO [BSA].[dbo].[BSA_MissionLog]

           ([a]

           ,[b])

     VALUES

           ('1'

           ,'1'

           )

 

select id = scope_identity()";//这里是最重要的一段话.

        DbCommand dbcomm = db.GetSqlStringCommand(strSql);

        DataSet ds = db.ExecuteDataSet(dbcomm);

        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

        {

            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)

{

                Response.Write("第"+i+"行"+j+"列:"+ds.Tables[0].Rows[i][j].ToString());

}

        }

    }

}

 

下面的代码是使用ado.net 2.0的代码:

SqlConnection con = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=table1;Persist Security Info=True;User ID=sa;Password=sa");

        try

        {

            string strSql = @"INSERT INTO Log

           ([a]

           ,[b])

     VALUES

           ('1'

           ,'1')

 

select id = scope_identity()";

            con.Open();

            SqlCommand com = new SqlCommand(strSql, con);

            DataSet ds = new DataSet();

 

            SqlDataAdapter da = new SqlDataAdapter(com);

            da.Fill(ds);

            con.Close();

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

            {

                for (int j = 0; j < ds.Tables[0].Columns.Count; j++)

                {

                    Response.Write("第" + i + "行" + j + "列:" + ds.Tables[0].Rows[i][j].ToString());

                }

            }

        }

        finally

        {

            con.Close();

        }

 

微软对这样的方法解释是:

此代码告诉 SQL Server 不要返回查询的行计数,然后执行 INSERT 语句,并返回刚刚为这个新行创建的 IDENTITY 值。da.Fill(ds)语句返回的记录集有一行和一列,其中包含了这个新的 IDENTITY 值。如果没有此语句,则会首先返回一个空的记录集(因为 INSERT 语句不返回任何数据),然后会返回第二个记录集,第二个记录集中包含 IDENTITY 值。这可能有些令人困惑,尤其是因为您从来就没有希望过 INSERT 会返回记录集。之所以会发生此情况,是因为 SQL Server 看到了这个行计数(即一行受到影响)并将其解释为表示一个记录集。因此,真正的数据被推回到了第二个记录集。


转载于:https://www.cnblogs.com/winnerzone/archive/2007/06/11/779509.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值