转载OleDb操作Access数据库:新增记录时获取自动编号的主键值
生活随笔
收集整理的這篇文章主要介紹了
转载OleDb操作Access数据库:新增记录时获取自动编号的主键值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//打開數據庫的一般方法 OleDbConnection cnn =?new?OleDbConnection(sCnn); cnn.Open(); DataTable table =?new?DataTable(); try { ????OleDbCommand cmd =?new?OleDbCommand(sCommand, cnn); ????cmd.CommandType = cmdType; ????//構建DataAdapter ????OleDbDataAdapter adapter =?new?OleDbDataAdapter(cmd); ????//填充數據 ????table =?new?DataTable(sDataTableName); ????adapter.Fill(table); ????cnn.Close(); ????table.PrimaryKey =?new?DataColumn[1] { table.Columns[0] }; ????OleDbCommandBuilder builder =?new?OleDbCommandBuilder(adapter); ????builder.QuotePrefix =?"["; ????builder.QuoteSuffix =?"]"; ????adapter.InsertCommand = builder.GetInsertCommand(); ????adapter.DeleteCommand = builder.GetDeleteCommand(); ????adapter.UpdateCommand = builder.GetUpdateCommand(); ????adapter.RowUpdated +=?new?OleDbRowUpdatedEventHandler(OnRowUpdated); } catch { } ?? ?? //======================== //OleDbRowUpdatedEventHandler實例 protected?void?OnRowUpdated(object?sender, OleDbRowUpdatedEventArgs e) { ????if?((e.Status == UpdateStatus.Continue) && e.StatementType == StatementType.Insert) ????{ ????????int?newID = 0; ????????OleDbCommand cmdGetId =?new?OleDbCommand("SELECT @@IDENTITY", e.Command.Connection); ????????newID = (int)cmdGetId.ExecuteScalar(); ????????e.Row["id"] = newID; ????????if?(newID == 0) ????????{ ????????????MessageBox.Show("獲取ID值錯誤!"); ????????} ????} } ?? //======================== //修改row的數據 ????System.Data.DataTable tblChange = table.GetChanges(); ????affectRowCount = adapter.Update(tblChange); ????if?(mode == modeNew) ????{ ????????row["id"] = tblChange.Rows[0]["id"]; ????} ????table.AcceptChanges();
?
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的转载OleDb操作Access数据库:新增记录时获取自动编号的主键值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JSTL解析——001
- 下一篇: python中字符串编码转换