ASP.NET獲得當前插入行主鍵的代碼
作者:asidy
本文介紹了在asp.net中向數據庫中插入數據時如何獲得當前插入行的主鍵。
我們在進行數據庫插入或更新操作的時候,有時我們需要知道當前插入行的數據庫表的主鍵值。那么如何實現asp.net獲得當前插入行的主鍵呢?下面的代碼將實現獲得插入數據時的主鍵值:
- // 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"; //查找主鍵:asp.net獲得當前插入行主鍵
- int newCustomerID = Convert.ToInt32(command.ExecuteScalar());
- connection.Close();//關閉連接
- _CustomerID = newCustomerID;
- return newCustomerID;
- }
【編輯推薦】
- ASP.NET DetailsView中顯示選中產品的詳細信息
- ASP.NET 2.0數據教程:GridView選擇行
- ASP.NET 2.0數據教程:GridView顯示數據
- ASP.NET 2.0中添加GridView到頁面
- 新增ASP.NET頁面時的注意事項
責任編輯:book05
來源:
cnblogs