如何在asp.net中更新数据时获得当前行主键?

来源:互联网 发布:简述网络教学的定义 编辑:程序博客网 时间:2024/05/18 00:00

如何在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;  

原创粉丝点击