zoukankan      html  css  js  c++  java
  • <转载>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();
  • 相关阅读:
    设计模式学习(十二) 责任链模式
    设计模式学习(十一) 享元模式
    设计模式学习(十) 外观模式
    设计模式学习(九) 装饰模式
    设计模式学习(八) 组合模式
    设计模式学习(七) 桥接模式
    设计模式学习(六) 代理模式
    设计模式学习(五) 适配器模式
    设计模式学习(四) 原型模型
    设计模式(三) 建造者模式
  • 原文地址:https://www.cnblogs.com/xiexiaokui/p/2837949.html
Copyright © 2011-2022 走看看