Beispiel #1
0
        public void InsertUpdateDelete_Speed()
        {
            var dbFactory    = new DbFactory(SqlClientFactory.Instance);
            var cmdGenerator = new DbCommandBuilder(dbFactory);

            var testData = new Dictionary <string, object> {
                { "name", "Test" },
                { "age", 20 },
                { "created", DateTime.Now }
            };
            var testQuery = new Query("test", (QField)"id" == (QConst)5);
            var stopwatch = new Stopwatch();

            int iterations = 0;

            stopwatch.Start();
            while (iterations < 500)
            {
                iterations++;
                var insertCmd = cmdGenerator.GetInsertCommand("test", testData);
                var updateCmd = cmdGenerator.GetUpdateCommand(testQuery, testData);
                var deleteCmd = cmdGenerator.GetDeleteCommand(testQuery);
            }

            stopwatch.Stop();
            Console.WriteLine("Speedtest for DbCommandGenerator Insert+Update+Delete commands ({1} times): {0}", stopwatch.Elapsed, iterations);
        }
        public void UpdateTable(string tablename, CorreggiDateListiniDS ds)
        {
            string query = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}", tablename);

            using (DbDataAdapter a = BuildDataAdapter(query))
            {
                try
                {
                    a.ContinueUpdateOnError = false;
                    DataTable        dt  = ds.Tables[tablename];
                    DbCommandBuilder cmd = BuildCommandBuilder(a);
                    a.UpdateCommand = cmd.GetUpdateCommand();
                    a.DeleteCommand = cmd.GetDeleteCommand();
                    a.InsertCommand = cmd.GetInsertCommand();
                    a.Update(dt);
                }
                catch (DBConcurrencyException ex)
                {
                }
                catch
                {
                    throw;
                }
            }
        }
Beispiel #3
0
        protected void ConfigureAdapterCommands(DataTable dt, DbDataAdapter da, DbCommandBuilder cb)
        {
            bool   isIdentity;
            string identityField;

            switch (DBEngine)
            {
            case DBEngines.MSSqlServer:
                break;

            case DBEngines.Oracle:
            {
                da.InsertCommand = cb.GetInsertCommand();
                da.UpdateCommand = cb.GetUpdateCommand();
                da.DeleteCommand = cb.GetDeleteCommand();

                OracleDbType identityType;
                MapOracleIdentityField(dt, out isIdentity, out identityField, out identityType);
                if (isIdentity)
                {
                    OracleDataAdapter oDa = (OracleDataAdapter)da;
                    da.InsertCommand.CommandText += string.Format(" RETURNING {0}{1}{2} INTO :{3}{4}",
                                                                  TablePrefix, identityField.ToUpper(), TableSuffix,
                                                                  OracleParamIdentityPrefix, identityField);
                    oDa.InsertCommand.Parameters.Add(OracleParamIdentityPrefix + identityField, identityType).Direction = ParameterDirection.Output;
                }
                else
                {
                    da.InsertCommand = cb.GetInsertCommand();
                }
                break;
            }
            }
        }
Beispiel #4
0
        protected override async Task <U3Pair> RunBatchingProxiedDbDataAdapterAsync(List <TestTable> randomDataSource, BatchingFakeProxiedDbDataAdapter adapter)
        {
            using (DbCommandBuilder <FakeDbCommand> cmdBuilder = await adapter.CreateCommandBuilderAsync().ConfigureAwait(false))
            {
                DataTable dataTable = new DataTable();

                // `.Fill` returns the number of rows in the first table, not any subsequent tables. Yes, that's silly.
                Int32 rowsInFirstTable = adapter.Fill(dataTable);
                rowsInFirstTable.ShouldBe(40);

                //
                Dictionary <String, Int32> rowsModified = DataTableMethods.MutateDataTable(dataTable);

                //
                adapter.UpdateCommand = cmdBuilder.GetUpdateCommand();
                adapter.UpdateCommand.NonQueryResultRowCountValue = (cmd) => DataTableMethods.GetUpdateStatementNonQueryResultRowCountValue(expectedTableName: "TODO", adapter, dataTable, cmd, rowsModified);

                DataRow[] rows = dataTable.Rows.Cast <DataRow>().ToArray();

                Int32 updatedRows = await adapter.Update3Async(dataTable);

//              updatedRows.ShouldBe( rowsModified );

                return(dataTable, rowsModified, updatedRows);
            }
        }
 public static void PrintSqlCommandBuilder(DbCommandBuilder commandBuilder, string sComment /* = "" */)
 {
     PrintIfNotEmpty(sComment);
     PrintDataAdapter(commandBuilder.DataAdapter, "");
     Debug.WriteLine("SqlCommandBuilder InsertCommand " + commandBuilder.GetInsertCommand().CommandText);
     Debug.WriteLine("SqlCommandBuilder UpdateCommand " + commandBuilder.GetUpdateCommand().CommandText);
     Debug.WriteLine("SqlCommandBuilder DeleteCommand " + commandBuilder.GetDeleteCommand().CommandText);
 }
Beispiel #6
0
        /// <summary>
        /// 设置DBDataAdapter的sql
        /// </summary>
        /// <param name="adapter"></param>
        public static void SetDbDataAdapterCommand(DbDataAdapter adapter)
        {
            DbCommandBuilder cb = CreateCommandBuilder(adapter);

            adapter.UpdateCommand = cb.GetUpdateCommand();
            adapter.InsertCommand = cb.GetInsertCommand();
            adapter.DeleteCommand = cb.GetDeleteCommand();
        }
Beispiel #7
0
        /// <summary>
        /// 更新系SQLの自動生成を行う
        /// </summary>
        /// <param name="factory">データ取得時に指定されたデータプロバイダのDbProviderFactory</param>
        /// <param name="adapter">データ取得時に生成したDbDataAdapter</param>
        /// <param name="log">実行ログ出力先のStringBuilder</param>
        private static void CreateUpdateCommand(DbProviderFactory factory, DbDataAdapter adapter, StringBuilder log)
        {
            // CommandBuilderを生成し、DbDataAdapterに関連付ける
            DbCommandBuilder cb = factory.CreateCommandBuilder();

            cb.DataAdapter = adapter;

            log.AppendFormat("< {0} クラスのオブジェクトによって動的に生成された SQL >", cb.GetType().ToString());
            log.AppendLine();

            // INSERT文を生成する
            log.AppendLine("INSERT SQL コマンド:");
            log.AppendLine(cb.GetInsertCommand().CommandText);
            log.AppendLine();
            log.AppendLine("INSERT SQL コマンド パラメータ:");
            foreach (DbParameter param in cb.GetInsertCommand().Parameters)
            {
                log.AppendFormat("{0} => DbType = {1}, SourceColumn = {2}", param.ParameterName, param.DbType, param.SourceColumn);
                log.AppendLine();
            }
            log.AppendLine().AppendLine();

            // UPDATE文を生成する
            log.AppendLine("UPDATE SQL コマンド:");
            log.AppendLine(cb.GetUpdateCommand().CommandText);
            log.AppendLine();
            log.AppendLine("UPDATE SQL コマンド パラメータ:");
            foreach (DbParameter param in cb.GetUpdateCommand().Parameters)
            {
                log.AppendFormat("{0} => DbType = {1}, SourceColumn = {2}", param.ParameterName, param.DbType, param.SourceColumn);
                log.AppendLine();
            }
            log.AppendLine().AppendLine();

            // DELETE文を生成する
            log.AppendLine("DELETE SQL コマンド:");
            log.AppendLine(cb.GetDeleteCommand().CommandText);
            log.AppendLine();
            log.AppendLine("DELETE SQL コマンド パラメータ:");
            foreach (DbParameter param in cb.GetDeleteCommand().Parameters)
            {
                log.AppendFormat("{0} => DbType = {1}, SourceColumn = {2}", param.ParameterName, param.DbType, param.SourceColumn);
                log.AppendLine();
            }
        }
 public AdapterStatement(DbCommand selectCommand, DbCommandBuilder commandBuilder)
 {
     _commandBuilder        = commandBuilder;
     _adapter               = commandBuilder.DataAdapter;
     _adapter.SelectCommand = selectCommand;
     _adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
     _adapter.InsertCommand = commandBuilder.GetInsertCommand();
     _adapter.DeleteCommand = commandBuilder.GetDeleteCommand();
 }
Beispiel #9
0
        public int ActualizaObjetoPersistenteByClavePrimaria <T>(T beanOriginal, T beanModificado, DbConnection connection, DbTransaction tr)
        {
            //calculamos el tipo de T para obtener información sobre los objetos que queremos contruir
            //a partir de la base de datos
            Type tipo = typeof(T);

            //comprobamos que el tipo sea persistente
            if (tipo.IsDefined(typeof(ObjetoPersistente), false))
            {
                //generamos el nombre de la tabla por defecto a partir del nombre del tipo
                string nombreTabla = CalcularNombreTabla(tipo);



                #region Calcular el comando de inserccion
                DbCommandBuilder comandBuilder = CrearDBCommandBuilder(nombreTabla, connection, tr);

                DbCommand comandoInsert = comandBuilder.GetUpdateCommand(true);
                if (tr != null)
                {
                    comandoInsert.Transaction = tr;
                }
                StringBuilder sql = new StringBuilder(comandoInsert.CommandText.Split("WHERE".ToCharArray())[0]);

                AtributoPersistente k = GetFieldInfoPrimaryKey(beanOriginal);

                if (k != null)
                {
                    sql.AppendFormat(" WHERE {0}=:{0}", k.MapeadoPor);
                }

                #endregion

                //connection.Close();

                //connection.Open();

                DbCommand updateCommand = _factoria.CreateCommand();
                if (tr != null)
                {
                    updateCommand.Transaction = tr;
                }
                updateCommand.CommandText = sql.ToString();
                updateCommand.Connection  = connection;

                DbParameterCollection parametrosComando = updateCommand.Parameters;

                //rellenamos las condiciones del comando para buscar el bean a modificar
                RellenarParametrosFrom <T>(beanOriginal, parametrosComando, "Original_");

                //rellenamos los valores que queremos modificar
                RellenarParametrosFrom <T>(beanModificado, parametrosComando);

                return(updateCommand.ExecuteNonQuery());
            }
            return(-1);
        }
Beispiel #10
0
        /// <summary>
        /// Builds UPDATE command.
        /// </summary>
        public void BuildUpdateCommand()
        {
            if (Adapter == null || Adapter.DeleteCommand != null)
            {
                return;
            }

            EnsureBuilder();
            Adapter.UpdateCommand = _Builder.GetUpdateCommand();
        }
 /// <summary>
 /// Rellena los DbCommands (INSERT, UPDATE, DELETE) del Adaptador
 /// </summary>
 /// <param name="adapter">Adaptador a llenar</param>
 private void FillAdapterCommands(DbDataAdapter adapter)
 {
     using (DbDataAdapter auxAdapter = ConnectorFactory.GetDataAdapter(Server))
     {
         auxAdapter.SelectCommand = adapter.SelectCommand;
         using (DbCommandBuilder commandBuilder = ConnectorFactory.GetCommandBuilder(Server, auxAdapter))
         {
             adapter.DeleteCommand = commandBuilder.GetDeleteCommand(true);
             adapter.UpdateCommand = commandBuilder.GetUpdateCommand(true);
             adapter.InsertCommand = commandBuilder.GetInsertCommand(true);
             SetupTransactionAdapterCommands(adapter);
         }
     }
 }
Beispiel #12
0
        public int Update(DataTable dt)
        {
            if (String.IsNullOrEmpty(dt.TableName))
            {
                throw new Exception("没有表名");
            }
            //貌似能自动打开释放连接

            DbDataAdapter adapter = null;
            DataTable     tempDt  = GetDataTable(dt.TableName, 1);                       //为了获取表的列数

            if (dt.PrimaryKey.Length == 0 || (tempDt.Columns.Count != dt.Columns.Count)) //如果没有主键或者传入的表列不完整则调用自定义的构造
            {
                adapter = CreateAdapter(dt);
            }
            else
            {
                DbCommand cmd = this.DbProviderFactoryInstance.CreateCommand();
                cmd.CommandText       = "select * from " + dt.TableName;
                adapter               = this.DbProviderFactoryInstance.CreateDataAdapter();
                adapter.SelectCommand = cmd;
                DbCommandBuilder commandBuilder = this.DbProviderFactoryInstance.CreateCommandBuilder();
                commandBuilder.DataAdapter = adapter;
                adapter.DeleteCommand      = commandBuilder.GetDeleteCommand(true);
                adapter.InsertCommand      = commandBuilder.GetInsertCommand(true);
                adapter.UpdateCommand      = commandBuilder.GetUpdateCommand(true);
            }

            string temp = "";

            foreach (DataColumn column in dt.Columns)   //查找是否有自动递增的自动 如果有并且数据库类型是sqlserver那么 加入运行插入自动递增字段
            {
                if (column.AutoIncrement)
                {
                    temp += "SET IDENTITY_INSERT  [" + dt.TableName + "] ON;";
                    break;
                }
            }

            adapter.InsertCommand.CommandText = temp + adapter.InsertCommand.CommandText;

            using (TransactionScope ts = new TransactionScope())
            {
                int result = adapter.Update(dt);
                ts.Complete();
                dt.AcceptChanges();
                return(result);
            }
        }
        public void UpdateRegistrazioneDS(string tablename, RilevazioniDS ds)
        {
            string query = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}", tablename);

            using (DbDataAdapter a = BuildDataAdapter(query))
            {
                a.ContinueUpdateOnError = false;
                DataTable        dt  = ds.Tables[tablename];
                DbCommandBuilder cmd = BuildCommandBuilder(a);
                a.UpdateCommand = cmd.GetUpdateCommand();
                a.DeleteCommand = cmd.GetDeleteCommand();
                a.InsertCommand = cmd.GetInsertCommand();
                a.Update(dt);
            }
        }
        public DatabaseReporter(DbProviderFactory factory, DbConnection connection)
        {
            this.connection = connection;

            watch = System.Diagnostics.Stopwatch.StartNew();

            DbCommand command = factory.CreateCommand();

            command.CommandText = "SELECT * FROM " + Properties.Settings.Default.databaseprefix + "output";
            command.Connection  = connection;

            kopadapter = factory.CreateDataAdapter();
            kopadapter.SelectCommand = command;
            DbCommandBuilder builder = factory.CreateCommandBuilder();

            builder.ConflictOption = ConflictOption.OverwriteChanges;
            builder.DataAdapter    = kopadapter;
            // Wanneer : Additional information: De Microsoft.Jet.OLEDB.4.0-provider is niet geregistreerd op de lokale computer.
            //  ==> draaien als x86
            kopadapter.InsertCommand = builder.GetInsertCommand();
            kopadapter.UpdateCommand = builder.GetUpdateCommand();
            kopadapter.DeleteCommand = builder.GetDeleteCommand();

            command             = factory.CreateCommand();
            command.CommandText = "SELECT * FROM " + Properties.Settings.Default.databaseprefix + "outputline";
            command.Connection  = connection;

            regeladapter = factory.CreateDataAdapter();
            regeladapter.SelectCommand = command;
            builder = factory.CreateCommandBuilder();
            builder.ConflictOption     = ConflictOption.OverwriteChanges;
            builder.DataAdapter        = regeladapter;
            regeladapter.InsertCommand = builder.GetInsertCommand();
            regeladapter.UpdateCommand = builder.GetUpdateCommand();
            regeladapter.DeleteCommand = builder.GetDeleteCommand();
        }
        internal void UpdateTable(string tablename, ScheduleServicesDS ds)
        {
            string query = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}", tablename);

            using (DbDataAdapter a = BuildDataAdapter(query))
            {
                a.ContinueUpdateOnError = false;
                DataTable        dt  = ds.Tables[tablename];
                DbCommandBuilder cmd = BuildCommandBuilder(a);
                a.UpdateCommand = cmd.GetUpdateCommand();
                a.DeleteCommand = cmd.GetDeleteCommand();
                a.InsertCommand = cmd.GetInsertCommand();
                a.Update(dt);
            }
        }
Beispiel #16
0
        private void frmanimals_Load(object sender, EventArgs e)
        {
            DbCommand idbCommand = Connection.provideConnection().CreateCommand();

            idbCommand.CommandText = "select * from `animals`";
            ad = returnAdapter();
            DbCommandBuilder builder = returnBuilder();

            builder.DataAdapter = ad;
            ad.SelectCommand    = idbCommand;
            ad.Fill(this.newDataSet.animals);
            ad.DeleteCommand = builder.GetDeleteCommand();
            ad.UpdateCommand = builder.GetUpdateCommand();
            ad.InsertCommand = builder.GetInsertCommand();
        }
Beispiel #17
0
        public void UpdateDatabase(DataTable dt, string selectSql)
        {
            DbDataAdapter    dba     = makeDBA(myType, selectSql);
            DbCommandBuilder builder = openBuilder(myType);

            builder.DataAdapter = dba;

            dba.InsertCommand = builder.GetInsertCommand();
            dba.UpdateCommand = builder.GetUpdateCommand();
            dba.DeleteCommand = builder.GetDeleteCommand();

            dba.UpdateBatchSize = 100;
            dba.Update(dt);
            dt.AcceptChanges();
        }
Beispiel #18
0
        public bool SaveDataTable(DataTable dataTable, string tableName)
        {
            string sql = string.Format("select * from {0}", tableName);

            DbDataAdapter    sda = CurrentDBConnection.CreateDbDataAdapter(sql, GetConnection());
            DbCommandBuilder scb = CurrentDBConnection.CreateCommandBuilder();

            sda.InsertCommand = scb.GetInsertCommand();
            sda.UpdateCommand = scb.GetUpdateCommand();
            sda.DeleteCommand = scb.GetDeleteCommand();

            sda.Fill(dataTable);
            var r = sda.Update(dataTable);

            return(true);
        }
Beispiel #19
0
        public virtual bool UpDateTable(DataTable table, string tableName)
        {
            DbCommand command = GetDbCommand();

            command.CommandText = string.Format("SELECT * FROM [{0}]", tableName);
            command.Connection  = GetDbConnection();
            DbDataAdapter    adapter = GetDbDataAdapter(command);
            DbCommandBuilder builder = GetDbCommandBuilder(adapter);

            adapter.InsertCommand = builder.GetInsertCommand();
            adapter.DeleteCommand = builder.GetDeleteCommand();
            adapter.UpdateCommand = builder.GetUpdateCommand();
            int cou = adapter.Update(table);

            return(cou > 0);
        }
Beispiel #20
0
        /// <summary>
        /// 更新table到数据库
        /// </summary>
        /// <param name="dt">要更新的表</param>
        /// <param name="sql">要执行的查询语句</param>
        /// <returns></returns>
        public int UpdateTable(DataTable dt, string sql)
        {
            ErrorMessage = "";
            int          affect     = 0;
            DbConnection connection = providerFactory.CreateConnection();

            using (DbCommand command = CreateDbCommand(sql, null, CommandType.Text))
            {
                using (DbDataAdapter adapter = providerFactory.CreateDataAdapter())
                {
                    command.CommandType = CommandType.Text;
                    //command.CommandText = sql;
                    command.CommandText         = dt.ExtendedProperties["SQL"].ToString();
                    adapter.SelectCommand       = command;
                    adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                    using (DbCommandBuilder cb = providerFactory.CreateCommandBuilder())
                    {
                        try
                        {
                            cb.DataAdapter        = adapter;
                            adapter.InsertCommand = cb.GetInsertCommand();
                            adapter.UpdateCommand = cb.GetUpdateCommand();
                            adapter.DeleteCommand = cb.GetDeleteCommand();

                            adapter.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;
                            adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None;
                            adapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None;

                            command.Connection.Open();
                            if (dt.GetChanges() != null)
                            {
                                affect = adapter.Update(dt.GetChanges());
                                dt.AcceptChanges();
                            }
                            command.Connection.Close();
                        }
                        catch (Exception ex)
                        {
                            ErrorMessage = ex.Message;
                            affect       = -1;
                        }
                    }
                }
            }

            return(affect);
        }
Beispiel #21
0
 private void PerformUpdate(DataSet pDs, List <string> pTableOrder)
 {
     foreach (string MyTableName in pTableOrder)
     {
         DataRow[] MyRows = pDs.Tables[MyTableName].Select("", "", DataViewRowState.ModifiedCurrent);
         if (MyRows.Length > 0)
         {
             m_CurrentUpdating = MyTableName;
             DbDataAdapter    MyDa = CreateDataAdapter(pDs, MyTableName);
             DbCommandBuilder MyCB = CreateCommandBuilder(MyDa);
             MyDa.UpdateCommand             = MyCB.GetUpdateCommand();
             MyDa.UpdateCommand.Transaction = m_Trans;
             MyDa.UpdateBatchSize           = m_BatchSize;
             MyDa.Update(MyRows);
         }
     }
 }
Beispiel #22
0
        //Erzeugt einen DbDataAdapter für die Verbindung und den SQL-Befehl
        //Benötigt eine DbProviderFactory, Eine Verbindung und ein SQL-Befehl
        public static DbDataAdapter CreateDbDataAdapter(DbProviderFactory dbProviderFactory, DbConnection dbConnection, string sql)
        {
            DbCommand dbSelectCommand = dbProviderFactory.CreateCommand();

            dbSelectCommand.Connection  = dbConnection;
            dbSelectCommand.CommandText = sql;
            DbDataAdapter dbDataAdapter = dbProviderFactory.CreateDataAdapter();

            dbDataAdapter.SelectCommand = dbSelectCommand;
            DbCommandBuilder dbCommandBuilder = dbProviderFactory.CreateCommandBuilder();

            dbCommandBuilder.DataAdapter = dbDataAdapter;
            dbDataAdapter.InsertCommand  = dbCommandBuilder.GetInsertCommand();
            dbDataAdapter.UpdateCommand  = dbCommandBuilder.GetUpdateCommand();
            dbDataAdapter.DeleteCommand  = dbCommandBuilder.GetDeleteCommand();
            return(dbDataAdapter);
        }
Beispiel #23
0
        public void UpdateDistintaBaseTable(ArticoliDS ds)
        {
            string query = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}", ds.DIBA.TableName);

            using (DbDataAdapter a = BuildDataAdapter(query))
            {
                InstallRowUpdatedHandler(a, UpdateDistintaBaseHander);
                a.ContinueUpdateOnError = false;
                DataTable        dt  = ds.DIBA;
                DbCommandBuilder cmd = BuildCommandBuilder(a);
                a.AcceptChangesDuringFill = true;
                a.UpdateCommand           = cmd.GetUpdateCommand();
                a.DeleteCommand           = cmd.GetDeleteCommand();
                a.InsertCommand           = cmd.GetInsertCommand();

                a.Update(dt);
            }
        }
Beispiel #24
0
        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public bool UpdateDataTable(DataTable dt, string selectSql)
        {
            bool resule = true;

            if (dt == null || dt.Rows.Count <= 0)
            {
                return(resule);
            }
            this.Open();
            DbTransaction trans = connection.BeginTransaction();

            try
            {
                DbProviderFactory dbfactory = GetFactory();
                DbCommand         cmd       = connection.CreateCommand();
                cmd.CommandText = selectSql;
                DbDataAdapter dr = dbfactory.CreateDataAdapter();
                dr.SelectCommand             = cmd;
                dr.SelectCommand.Transaction = trans;
                DbCommandBuilder builder = dbfactory.CreateCommandBuilder();

                builder.QuotePrefix    = "[";
                builder.QuoteSuffix    = "]";
                builder.ConflictOption = ConflictOption.OverwriteChanges;
                builder.SetAllValues   = false;
                builder.DataAdapter    = dr;
                dr.InsertCommand       = builder.GetInsertCommand();
                dr.UpdateCommand       = builder.GetUpdateCommand();
                dr.DeleteCommand       = builder.GetDeleteCommand();
                resule = dr.Update(dt) > 0;
                // dt.AcceptChanges();
                trans.Commit();
                return(resule);
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw new Exception(ex.Message);
            }
            finally
            {
                this.Close();
            }
        }
        public void UpdateTableSPControlli(SchedeProcessoDS ds)
        {
            string query = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0}", ds.SPCONTROLLI.TableName);

            using (DbDataAdapter a = BuildDataAdapter(query))
            {
                InstallRowUpdatedHandler(a, UpdateSPCOntrolloHander);

                a.ContinueUpdateOnError = false;
                DataTable        dt  = ds.SPCONTROLLI;
                DbCommandBuilder cmd = BuildCommandBuilder(a);
                a.AcceptChangesDuringFill = true;
                a.UpdateCommand           = cmd.GetUpdateCommand();
                a.DeleteCommand           = cmd.GetDeleteCommand();
                a.InsertCommand           = cmd.GetInsertCommand();

                a.Update(dt);
            }
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            //DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
            DbProviderFactory factory    = DbProviderFactories.GetFactory("System.Data.SqlClient");
            DbConnection      connection = factory.CreateConnection();

            connection.ConnectionString = SQL_CONN;
            using (connection) {
                //runClassicSelect(connection, factory);
                string    sql     = "SELECT id, name FROM People";
                DbCommand command = connection.CreateCommand();
                command.CommandText = sql;

                DbDataAdapter adapter = factory.CreateDataAdapter();
                adapter.SelectCommand = command;

                DbCommandBuilder builder = factory.CreateCommandBuilder();
                builder.DataAdapter = adapter;

                adapter.InsertCommand = builder.GetInsertCommand();
                adapter.UpdateCommand = builder.GetUpdateCommand();
                adapter.DeleteCommand = builder.GetDeleteCommand();

                DataTable people = new DataTable("People");
                adapter.Fill(people);
                print(people);

                people.Rows.Add(23, "Albert");
                print(people);
                Console.ReadKey();
                adapter.Update(people);

                foreach (DataRow row in people.Select("id = 23"))
                {
                    row.Delete();
                }
                print(people);
                Console.ReadKey();
                adapter.Update(people);
            }
            Console.ReadKey();
        }
        /// <summary>
        /// Gets the adapter.
        /// </summary>
        /// <param name="factory">The factory.</param>
        /// <param name="connectionConfiguration">The connection configuration.</param>
        /// <param name="query">The query.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">factory;The expected provider factory is not here.</exception>
        /// <exception cref="System.ArgumentException">
        /// The DBMS Connection string was not specified.
        /// or
        /// The DBMS query was not specified.
        /// </exception>
        public static DbDataAdapter GetAdapter(DbProviderFactory factory, string connectionConfiguration, string query)
        {
            if (factory == null)
            {
                throw new ArgumentNullException("factory", "The expected provider factory is not here.");
            }
            if (string.IsNullOrEmpty(connectionConfiguration))
            {
                throw new ArgumentException("The DBMS Connection string was not specified.");
            }
            if (string.IsNullOrEmpty(query))
            {
                throw new ArgumentException("The DBMS query was not specified.");
            }

            DbDataAdapter adapter = factory.CreateDataAdapter();

            if (string.IsNullOrEmpty(connectionConfiguration) && string.IsNullOrEmpty(query))
            {
                return(adapter);
            }

            DbConnection connection = factory.CreateConnection();

            connection.ConnectionString = connectionConfiguration;

            DbCommand selectCommand = factory.CreateCommand();

            selectCommand.CommandText = query;
            selectCommand.Connection  = connection;

            DbCommandBuilder builder = factory.CreateCommandBuilder();

            builder.DataAdapter   = adapter;
            adapter.SelectCommand = selectCommand;

            adapter.DeleteCommand = builder.GetDeleteCommand();
            adapter.InsertCommand = builder.GetInsertCommand();
            adapter.UpdateCommand = builder.GetUpdateCommand();

            return(adapter);
        }
        protected virtual DbDataAdapter CreateDbDataAdapter(string tableName)
        {
            DbCommand dbSelectCommand = _aData.ProviderFactory.CreateCommand();

            dbSelectCommand.Connection  = _dbConnection;
            dbSelectCommand.CommandText = string.Format("SELECT * FROM {0}", tableName);

            DbDataAdapter dbDataAdapter = _aData.ProviderFactory.CreateDataAdapter();

            dbDataAdapter.SelectCommand = dbSelectCommand;
            // --- fertig, wenn keine schreibenden Datenbankzugriffe erforderlich ----

            DbCommandBuilder dbCommandBuilder = _aData.ProviderFactory.CreateCommandBuilder();

            dbCommandBuilder.DataAdapter = dbDataAdapter;
            dbDataAdapter.InsertCommand  = dbCommandBuilder.GetInsertCommand();
            dbDataAdapter.UpdateCommand  = dbCommandBuilder.GetUpdateCommand();
            dbDataAdapter.DeleteCommand  = dbCommandBuilder.GetDeleteCommand();

            return(dbDataAdapter);
        }
Beispiel #29
0
        public void UpdateTable(DataSet dataSet)
        {
            int iAffected = 0;

            try
            {
                ObjDataAdapter.SelectCommand.CommandText = MstrQuery;
                ObjCommand.CommandType        = CommandType.StoredProcedure;
                ObjCommandBuilder.DataAdapter = ObjDataAdapter;

                ObjDataAdapter.InsertCommand = ObjCommandBuilder.GetInsertCommand();
                ObjDataAdapter.UpdateCommand = ObjCommandBuilder.GetUpdateCommand();
                ObjDataAdapter.DeleteCommand = ObjCommandBuilder.GetDeleteCommand();

                iAffected = ObjDataAdapter.Update(dataSet);
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message, ex);
            }
        }
Beispiel #30
0
        public void Save()
        {
            if (Layerers.Count == 0 && ManualLayerers.Count == 0 && ds.HasChanges() == false)
            {
                return;
            }
            grid.ApplyEditAndEnd();
            PreCommit();
            if (ds.HasChanges() == false)
            {
                return;
            }

            Adapter.UpdateCommand = builder.GetUpdateCommand(); //might be reduant
            Adapter.Update(ds);
            _refresh_doPreDisplay = true;
            //_do_reorder = true;
            Open();
            ds.AcceptChanges();
            Close();
        }