ASP.NET獲得當(dāng)前插入行主鍵的代碼
作者:asidy
本文介紹了在asp.net中向數(shù)據(jù)庫中插入數(shù)據(jù)時(shí)如何獲得當(dāng)前插入行的主鍵。
我們?cè)谶M(jìn)行數(shù)據(jù)庫插入或更新操作的時(shí)候,有時(shí)我們需要知道當(dāng)前插入行的數(shù)據(jù)庫表的主鍵值。那么如何實(shí)現(xiàn)asp.net獲得當(dāng)前插入行的主鍵呢?下面的代碼將實(shí)現(xiàn)獲得插入數(shù)據(jù)時(shí)的主鍵值:
- // asp.net獲得當(dāng)前插入行主鍵
- //在數(shù)據(jù)表里創(chuàng)建一個(gè)新行,并把當(dāng)前屬性的值插入對(duì)應(yīng)的列中
- public int Create()
- {
- //建立數(shù)據(jù)庫連接
- SqlConnection connection = new SqlConnection(_Connectionstring);
- connection.open();//打開數(shù)據(jù)庫連接
- //建立數(shù)據(jù)庫連接對(duì)象
- SqlCommand command = new SqlCommand("insert into Customers "
- +"(LastName,FirstName,Address,City,State,Zip,Phone,"
- +"SignUpDate) values (@LastName,@FirstName,@Address,"
- +"@City,@Zip,@Phone,@SignUpDate)",connection);
- //將要插入的數(shù)據(jù)加入數(shù)據(jù)庫中
- 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();//執(zhí)行連接語句
- command.Parameters.Clear();
- command.CommandText = "select @@IDENTITY"; //查找主鍵:asp.net獲得當(dāng)前插入行主鍵
- int newCustomerID = Convert.ToInt32(command.ExecuteScalar());
- connection.Close();//關(guān)閉連接
- _CustomerID = newCustomerID;
- return newCustomerID;
- }
【編輯推薦】
- ASP.NET DetailsView中顯示選中產(chǎn)品的詳細(xì)信息
- ASP.NET 2.0數(shù)據(jù)教程:GridView選擇行
- ASP.NET 2.0數(shù)據(jù)教程:GridView顯示數(shù)據(jù)
- ASP.NET 2.0中添加GridView到頁面
- 新增ASP.NET頁面時(shí)的注意事項(xiàng)
責(zé)任編輯:book05
來源:
cnblogs