<转载>asp.net中向数据库中插入数据时如何获得当前插入行的主键?

我们在进行数据库插入或更新操作的时候,有时我们需要知道当前插入行的数据库表的主键值, 那么如何获得呢?下面的代码将实现获得插入数据时的主键值:

// 在数据表里创建一个新行,并把当前属性的值插入对应的列中
public int Create()
{
  //建立数据库连接
  SqlConnection connection = new SqlConnection(_Connectionstring);
  connection.open();//打开数据库连接
  //建立数据库连接对象
  SqlCommand command = new SqlCommand("insert into Customers "
   +"(LastName,FirstName,Address,City,State,Zip,Phone,"
   +"SignUpDate) values (@LastName,@FirstName,@Address,"
   +"@City,@Zip,@Phone,@SignUpDate)",connection);
   
   //将要插入的数据加入数据库中
   command.Parameters.AddWithValue("@LastName",_LastName);
   command.Parameters.AddWithValue("@FirstName",_FirstName);
   command.Parameters.AddWithValue("@Address",_Address);
   command.Parameters.AddWithValue("@City",_City);
   command.Parameters.AddWithValue("@Zip",_Zip);
   command.Parameters.AddWithValue("@Phone",_Phone);
   command.Parameters.AddWithValue("@SingUpDate",_SingUpDate);
   
   command.ExecuteNonQuery();//执行连接语句
   command.Parameters.Clear();
   command.CommandText = "select @@IDENTITY"; //查找主键
   int newCustomerID = Convert.ToInt32(command.ExecuteScalar());
   connection.Close();//关闭连接
   _CustomerID = newCustomerID;
   return newCustomerID;   
} 

  

转载于:https://www.cnblogs.com/ChangTan/archive/2011/12/27/2303768.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值