示例#1
0
        /// <summary>
        /// 更新表格
        /// </summary>
        /// <param name="query">sql语句</param>
        /// <param name="dt">需要更新的表</param>
        /// <param name="setAllValues">指定 update 语句中是包含所有列值还是仅包含更改的列值。</param>
        /// <param name="conflictOption">指定将如何检测和解决对数据源的相互冲突的更改。</param>
        /// <returns>对表进行更新操作</returns>
        public bool UpdateTable(string query, DataTable dt, bool setAllValues, ConflictOption conflictOption)
        {
            DbDataAdapter adapter = null;

            try
            {
                SetCommand(query, CommandType.Text);
                adapter = DbProvider.CreateDataAdapter();
                adapter.SelectCommand = command;
                DbCommandBuilder builder = DbProvider.CreateCommandBuilder();
                builder.DataAdapter    = adapter;
                builder.SetAllValues   = setAllValues;
                builder.ConflictOption = conflictOption;
                adapter.Update(dt);
                dt.AcceptChanges();
                return(true);
            }
            catch (Exception ex)
            {
                ErroMsg = ex.Message;
                return(false);
            }
            finally
            {
                this.parameters.Clear();
                adapter?.Dispose();
            }
        }
示例#2
0
 /// <summary>
 /// 更新数据库
 /// </summary>
 /// <param name="ds">DataSet</param>
 /// <param name="tableName">需要更新的数据库表名</param>
 public void UpdateData(DataSet ds, string tableName)
 {
     using (DbConnection connection = provider.CreateConnection())
     {
         connection.ConnectionString = connectionString;
         using (DbCommand cmd = provider.CreateCommand())
         {
             cmd.Connection  = connection;
             cmd.CommandText = "select * from " + tableName;
             try
             {
                 DbDataAdapter adapter = provider.CreateDataAdapter();
                 System.Data.Common.DbCommandBuilder dcb = provider.CreateCommandBuilder();
                 adapter.SelectCommand = cmd;
                 dcb.DataAdapter       = adapter;
                 adapter.Update(ds, tableName);
                 ds.AcceptChanges();
             }
             catch (DbException ex)
             {
                 connection.Close();
                 connection.Dispose();
                 throw new Exception(ex.Message);
             }
         }
     }
 }
示例#3
0
        private DbCommandBuilder CreateCommandBuilder()
        {
            var cmdbuilder = _providerFactory.CreateCommandBuilder();

            cmdbuilder.DataAdapter = InitializeDataAdapter();
            return(cmdbuilder);
        }
 private void Fill()
 {
     try
     {
         if (commandText == String.Empty)
         {
             return;
         }
         da = fact.CreateDataAdapter();
         da.SelectCommand             = conn.CreateCommand();
         da.SelectCommand.CommandText = commandText;
         var builder = fact.CreateCommandBuilder();
         set = new DataSet();
         da.Fill(set);
         users.Clear();
         DbDataReader dbDataReader = set.CreateDataReader();
         while (dbDataReader.Read())
         {
             users.Add(new User(dbDataReader.GetInt32(0), dbDataReader.GetString(1), dbDataReader.GetString(2), dbDataReader.GetString(3), dbDataReader.GetString(4), dbDataReader.GetString(5)));
         }
         selectedUser = null;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
示例#5
0
        private void LoadData()
        {
            // _usersAdapter
            _usersAdapter = _factory.CreateDataAdapter();

            DbCommand command = _factory.CreateCommand();

            command.Connection  = _connection;
            command.CommandText = "SELECT * FROM Users";

            DbCommandBuilder builder = _factory.CreateCommandBuilder(); // for what?

            builder.DataAdapter = _usersAdapter;

            _usersAdapter.SelectCommand = command;

            _usersAdapter.Fill(_usersDataSet, "Users");

            // _categoriesAdapter
            _categoriesAdapter = _factory.CreateDataAdapter();

            DbCommand command1 = _factory.CreateCommand();

            command1.Connection  = _connection;
            command1.CommandText = "SELECT * FROM UserCategories";

            DbCommandBuilder builder1 = _factory.CreateCommandBuilder(); // for what?

            builder1.DataAdapter = _categoriesAdapter;

            _categoriesAdapter.SelectCommand = command1;

            _categoriesAdapter.Fill(_categoriesDataSet, "UserCategories");
        }
示例#6
0
        private void AddLocaties(DbConnection connection, DbDataAdapter adapter, List <Adres> adresses)
        {
            string    queryLocatie   = "SELECT * FROM dbo.adresLocatieTest";
            DbCommand commandLocatie = sqlFactory.CreateCommand();

            commandLocatie.CommandText = queryLocatie;
            commandLocatie.Connection  = connection;
            adapter.SelectCommand      = commandLocatie;
            DbCommandBuilder builder = sqlFactory.CreateCommandBuilder();

            builder.DataAdapter   = adapter;
            adapter.InsertCommand = builder.GetInsertCommand();
            DataTable table = new DataTable();

            adapter.Fill(table);
            DataColumn[] keyColumns = new DataColumn[1]; // primary key voor deze kolom instellen
            keyColumns[0]    = table.Columns["Id"];      //idem
            table.PrimaryKey = keyColumns;               //idem
            foreach (Adres adres in adresses)
            {
                if (!table.Rows.Contains(adres.locatie.ID))
                {
                    DataRow row = table.NewRow();
                    row["Id"] = adres.locatie.ID;
                    row["x"]  = adres.locatie.x;
                    row["y"]  = adres.locatie.y;
                    table.Rows.Add(row);
                }
            }
            adapter.Update(table);
        }
示例#7
0
        public DataTable Get()
        {
            adapter.SelectCommand.CommandText = "select * from " + TableName;
            DbCommandBuilder cb = fact.CreateCommandBuilder();

            cb.DataAdapter = adapter;
            DataTable dt = new DataTable();

            adapter.Fill(dt);
            dt.Constraints.Add("pk_sno", dt.Columns[0], true);
            return(dt);
        }
示例#8
0
        /// <summary>
        /// <para>DbCommand の実行結果を DataSet へ投入します。</para>
        /// <para>スキーマ情報をマッピングする場合は mapppingSchema を true にします。</para>
        /// <para>各更新コマンドを生成する場合は createCommand を true にします。</para>
        /// <para>mappingSchema, createCommand は単一テーブルの操作の時のみ有効です。サブクエリによる単一テーブルの操作も有効にはなりません。</para>
        /// </summary>
        /// <param name="command">DbCommand オブジェクト。</param>
        /// <param name="providerFactory">DbProviderFactory オブジェクト。</param>
        /// <param name="dataSet">DataSet オブジェクト。</param>
        /// <param name="tableName">テーブル名。</param>
        /// <param name="schemaMapping">スキーマ情報のマッピングを行うかどうか。</param>
        /// <param name="commandCreate">各更新コマンドの生成を行うかどうか。</param>
        /// <returns>DbDataAdapter オブジェクト。</returns>
        public static DbDataAdapter FillToDataSet(this DbCommand command, DbProviderFactory providerFactory,
                                                  DataSet dataSet, string tableName = null, bool schemaMapping = false, bool commandCreate = false)
        {
            var da = providerFactory.CreateDataAdapter();

            da.SelectCommand = command;

            if (commandCreate)
            {
                var cb = providerFactory.CreateCommandBuilder();
                cb.DataAdapter   = da;
                da.InsertCommand = cb.GetInsertCommand(true);
                da.UpdateCommand = cb.GetUpdateCommand(true);
                da.DeleteCommand = cb.GetDeleteCommand(true);
            }

            if (tableName == string.Empty || tableName == null)
            {
                if (schemaMapping)
                {
                    da.FillSchema(dataSet, SchemaType.Mapped);
                }
                da.Fill(dataSet);
            }
            else
            {
                if (schemaMapping)
                {
                    da.FillSchema(dataSet, SchemaType.Mapped, tableName);
                }
                da.Fill(dataSet, tableName);
            }

            return(da);
        }
        /// <summary>
        /// 用DataTable对象更新数据库
        /// 1.DataTable的列可以多于数据库的列,不能少于数据库的列
        /// 2.不能用一个DataTable更新两个表的时候,需要调用两次GetChanges()方法获取两个DataTable来更新两个表
        /// 3.一个DataTable更新之后,需要用AcceptChanges来消除状态,然后再提交更新,重复更新会爆并发性错误
        /// </summary>
        /// <param name="ClientDataTable">用来跟更新的DataTable</param>
        /// <param name="SQLString">用来匹配DataTable格式的查询Sql语句</param>
        /// <returns>影响的行数</returns>
        public int SubmitDataTable(DataTable ClientDataTable, string SQLString)
        {
            int RowsCount = 0;

            if (ClientDataTable != null && ErrorMessage == null)
            {
                try
                {
                    SetSqlStringCommond(SQLString);
                    DbProviderFactory dbfactory     = DbProviderFactories.GetFactory(dbProviderName);
                    DbDataAdapter     dbDataAdapter = dbfactory.CreateDataAdapter();
                    dbDataAdapter.SelectCommand = dbCommand;
                    DbCommandBuilder DCB = dbfactory.CreateCommandBuilder();
                    DCB.DataAdapter = dbDataAdapter;
                    RowsCount       = dbDataAdapter.Update(ClientDataTable);
                    return(RowsCount);
                }
                catch (Exception ex)
                {
                    ShowException(ex);
                    return(0);
                }
            }
            else
            {
                return(0);
            }
        }
        public static bool GetParameterFormats([NotNull] this DbProviderFactory thisValue, [NotNull] out string nameFormat, [NotNull] out string placeholderFormat)
        {
            nameFormat        = FMT_PARAMETER_PLACEHOLDER_DEFAULT;
            placeholderFormat = FMT_PARAMETER_PLACEHOLDER_DEFAULT;

            DbCommandBuilder builder = thisValue.CreateCommandBuilder();

            if (builder == null)
            {
                return(false);
            }
            builder.RefreshSchema();

            string value = (string)GetParameterNameMethod.Invoke(builder, new object[] { "t" });

            if (string.IsNullOrEmpty(value))
            {
                return(false);
            }
            nameFormat = value.Length == 1 ? "{0}" : value.Left(value.Length - 1) + "{0}";

            value = (string)GetParameterPlaceholderMethod.Invoke(builder, new object[] { 0 });

            if (string.IsNullOrEmpty(value))
            {
                nameFormat = FMT_PARAMETER_PLACEHOLDER_DEFAULT;
                return(false);
            }

            placeholderFormat = value.Length < 3 ? "{0}" : value.Left(value.Length - 2) + "{0}";
            return(true);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            /* create a DbCommandBuilder and link it to the adapter */
            DbCommandBuilder commandBuilder = factory.CreateCommandBuilder();

            commandBuilder.DataAdapter = adapter;

            using (DbConnection con = factory.CreateConnection())
            {
                con.ConnectionString = cs;
                con.Open();

                /* The SelectCommand is already defined in the MainForm_Load */
                adapter.SelectCommand.Connection = con;

                /* link the auto-generated commands to the adapter */
                adapter.InsertCommand = commandBuilder.GetInsertCommand();
                adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
                adapter.DeleteCommand = commandBuilder.GetDeleteCommand();

                /*  instruct adapter to refresh the autoincrement primary key back to the client
                 *  NOTE: this will not work for the OleDb and MS Access. It should work with
                 *  other datasources such as MS SQL, Oracle etc, though.   */
                adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.Both;
                adapter.InsertCommand.CommandText     += Environment.NewLine + "SELECT @@IDENTITY as ID";

                MessageBox.Show(adapter.InsertCommand.CommandText);

                adapter.Update(table);
            }
        }
示例#12
0
        /// <summary>
        /// CommandType == CommandType.Text 일 경우 자동 파라메터 생성
        /// ex) query = "select * from tErrorLog where CreateDate between {0} and {1}"
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="command"></param>
        /// <param name="query"></param>
        /// <param name="parameters"></param>
        private void ProcessParameters(DbProviderFactory factory, DbCommand command, string query, params object[] parameters)
        {
            if (parameters == null || parameters.Length == 0)
            {
                command.CommandText = query;
            }
            else
            {
                IFormatProvider  formatProvider = CultureInfo.InvariantCulture;
                DbCommandBuilder commandBuilder = factory.CreateCommandBuilder();
                string           queryText      = query;

                for (int index = 0; index < parameters.Length; index++)
                {
                    string name        = getParameterName(commandBuilder, index);
                    string placeholder = getParameterPlaceholder(commandBuilder, index);
                    string i           = index.ToString("D", formatProvider);

                    DbParameter param = command.CreateParameter();
                    param.ParameterName = name;
                    param.Value         = parameters[index];
                    command.Parameters.Add(param);

                    queryText = queryText.Replace("{" + i + "}", placeholder);
                }

                command.CommandText = queryText.ToString();
            }
        }
示例#13
0
        private void ConfigureAdapter(DbConnection cnn, string tableName)
        {
            DbDataAdapter adapter;

            if (!_adapters.TryGetValue(tableName, out adapter))
            {
                DbCommandBuilder builder = _factory.CreateCommandBuilder();

                adapter = _factory.CreateDataAdapter();
                adapter.SelectCommand       = GetCommand(cnn, string.Format("SELECT * FROM {0}", builder.QuoteIdentifier(tableName)));
                adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

                builder.DataAdapter = adapter;

                // save default builder to quote identifiers
                if (_builder == null)
                {
                    _builder = builder;
                }

                _adapters.Add(tableName, adapter);
            }

            adapter.Fill(_dataSet, tableName);
        }
示例#14
0
    public static DbDataAdapter CrearDbDataAdapter(string proveedor, DbCommand ordenSe)
    {
        DbDataAdapter adaptador = null;

        try
        {
            // Crear DbProviderFactory y DbConnection.
            DbProviderFactory factoria = DbProviderFactories.GetFactory(proveedor);
            // Crear el objeto DbDataAdapter
            adaptador = factoria.CreateDataAdapter();
            adaptador.SelectCommand = ordenSe;
            DbCommandBuilder cb = factoria.CreateCommandBuilder();
            // Objeto DbDataAdapter para el que se generan
            // automáticamente instrucciones SQL
            cb.DataAdapter          = adaptador;
            adaptador.InsertCommand = cb.GetInsertCommand();
            adaptador.DeleteCommand = cb.GetDeleteCommand();
            adaptador.UpdateCommand = cb.GetUpdateCommand();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return(adaptador);
    }
示例#15
0
 public RelationalDatabaseWriterSimulator(PredefinedSqlConnection predefinedSqlConnection, SqlReplication sqlReplication)
     : base(predefinedSqlConnection)
 {
     _sqlReplication = sqlReplication;
     providerFactory = DbProviderFactories.GetFactory(predefinedSqlConnection.FactoryName);
     commandBuilder  = providerFactory.CreateCommandBuilder();
 }
示例#16
0
        public DbCommandBuilder CreateCommandBuilder(DbDataAdapter adapter)
        {
            var builder = factory.CreateCommandBuilder();

            builder.DataAdapter = adapter;
            return(builder);
        }
示例#17
0
        protected void Initialize(string databaseName, string querySelectRowString)
        {
            string providerName     = GetProviderNameByDBName(databaseName);
            string connectionString = GetConnectionStringByDBName(databaseName);

            // Create the DbProviderFactory and DbConnection.
            factory = DbProviderFactories.GetFactory(providerName);

            connection = factory.CreateConnection();
            connection.ConnectionString = connectionString;

            // Create the DbCommand.
            DbCommand SelectTableCommand = factory.CreateCommand();

            SelectTableCommand.CommandText = querySelectRowString;
            SelectTableCommand.Connection  = connection;

            adapter = factory.CreateDataAdapter();
            adapter.SelectCommand = SelectTableCommand;

            // Create the DbCommandBuilder.
            builder             = factory.CreateCommandBuilder();
            builder.DataAdapter = adapter;

            adapter.ContinueUpdateOnError = true;
        }
示例#18
0
        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SQLite");
                using (DbConnection connection = factory.CreateConnection())
                {
                    connection.ConnectionString = "Data Source  =D:\\person.db";
                    using (connection)
                    {
                        DbCommand command = connection.CreateCommand();
                        command.CommandText = "SELECT * FROM person";
                        command.CommandType = CommandType.Text;
                        command.Connection  = connection;

                        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();

                        adapter.Update(table);
                    }
                    MessageBox.Show("Saved/");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
示例#19
0
        /// <summary>
        /// 通过SQL得到一个DataTable,然后你可以在修改该DataTable,如:增加、修改、删除一些数据
        /// 然后在调用配套方法EndCommitTable,这样有效的提高SQL的性能因为不用查询整张表。
        /// </summary>
        /// <param name="factory">数据库实例的提供者</param>
        /// <param name="sqlQuery">SQL 查询语句.Eg:select * from Table where SysId=@SysId</param>
        /// <param name="parameter">查询语句后面的参数. Eg:new {SysId=111}</param>
        /// <param name="commandType">CommandType</param>
        /// <returns></returns>
        public DataTable BeginGetTable(DbProviderFactory factory, string sqlQuery, object parameter = null, CommandType commandType = CommandType.Text)
        {
            #region Validation

            Contract.Requires <ArgumentNullException>(factory != null);
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(sqlQuery));

            Contract.Ensures(adapter != null);
            Contract.Ensures(cmd != null);
            Contract.Ensures(builder != null);

            #endregion

            adapter = factory.CreateDataAdapter();
            builder = factory.CreateCommandBuilder();
            cmd     = factory.CreateCommand();

            DataTable dt = new DataTable();
            using (var command = PrepareExecute(sqlQuery, commandType, parameter))
            {
                adapter.SelectCommand = (DbCommand)command;
                builder.DataAdapter   = adapter;

                adapter.Fill(dt);
            }
            return(dt);
        }
示例#20
0
 internal TableManager(string tableName)
 {
     try
     {
         _da  = _DbProviderFactory.CreateDataAdapter();
         _cmd = _DbProviderFactory.CreateCommand();
         DbCommandBuilder cb = _DbProviderFactory.CreateCommandBuilder();
         _cmd.Connection   = Connection;
         cb.ConflictOption = ConflictOption.OverwriteChanges;
         cb.DataAdapter    = _da;
         _dt               = new DataTable();
         _temp             = new DataTable();
         _dt.TableName     = _temp.TableName = tableName;
         _cmd.CommandText  = "SELECT * FROM CAFEBD." + Table.TableName;
         _da.SelectCommand = _cmd;
         _da.InsertCommand = cb.GetInsertCommand();
         _da.DeleteCommand = cb.GetDeleteCommand();
         Recharge("1 = 2");
     }
     catch (Exception e)
     {
         Console.WriteLine("3");
         Console.WriteLine(e);
     }
 }
示例#21
0
        public void UpdateDataTable(string sql, DataTable dt)
        {
            using (DbCommand cmd = _cn.CreateCommand())
            {
                cmd.Connection     = _cn;
                cmd.CommandType    = CommandType.Text;
                cmd.CommandText    = sql;
                cmd.CommandTimeout = CommandTimeout;

                using (DbDataAdapter da = _factory.CreateDataAdapter())
                {
                    da.SelectCommand = cmd;

                    DbCommandBuilder cb = _factory.CreateCommandBuilder();
                    cb.DataAdapter   = da;
                    da.InsertCommand = cb.GetInsertCommand();
                    da.UpdateCommand = cb.GetUpdateCommand();
                    da.DeleteCommand = cb.GetDeleteCommand();

                    da.Update(dt);
                }
            }

            return;
        }
示例#22
0
 public int Update(DataTable dt)
 {
     try
     {
         string relTableName = dt.TableName;
         string SQLString    = string.Format("select * from {0}  ", relTableName);
         cmd.CommandText = SQLString;
         DbDataAdapter    adapter           = provider.CreateDataAdapter();
         DbCommandBuilder objCommandBuilder = provider.CreateCommandBuilder();
         adapter.SelectCommand         = cmd;
         objCommandBuilder.DataAdapter = adapter;
         adapter.DeleteCommand         = objCommandBuilder.GetDeleteCommand();
         adapter.InsertCommand         = objCommandBuilder.GetInsertCommand();
         adapter.UpdateCommand         = objCommandBuilder.GetUpdateCommand();
         foreach (DataRow Row in dt.Rows)
         {
             Row.EndEdit();
         }
         int count = adapter.Update(dt);
         dt.AcceptChanges();
         return(count);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
        private static object CreateObject(DbProviderFactory factory, ProviderSupportedClasses kindOfObject, string providerName)
        {
            switch (kindOfObject)
            {
            case ProviderSupportedClasses.DbConnection:
                return(factory.CreateConnection());

            case ProviderSupportedClasses.DbDataAdapter:
                return(factory.CreateDataAdapter());

            case ProviderSupportedClasses.DbParameter:
                return(factory.CreateParameter());

            case ProviderSupportedClasses.DbCommand:
                return(factory.CreateCommand());

            case ProviderSupportedClasses.DbCommandBuilder:
                return(factory.CreateCommandBuilder());

            case ProviderSupportedClasses.DbDataSourceEnumerator:
                return(factory.CreateDataSourceEnumerator());

            case ProviderSupportedClasses.CodeAccessPermission:
                return(factory.CreatePermission(PermissionState.None));
            }
            throw new InternalException(string.Format(CultureInfo.CurrentCulture, "Cannot create object of provider class identified by enum {0} for provider {1}", new object[] { Enum.GetName(typeof(ProviderSupportedClasses), kindOfObject), providerName }));
        }
示例#24
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);
        }
示例#25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cmd"></param>
        protected virtual void OnDeriveParameters(DbCommand cmd)
        {
            DbProviderFactory factory = DbProviderFactories.GetFactory(this.Provider);
            DbCommandBuilder  cb      = factory.CreateCommandBuilder();
            MethodInfo        method  = cb.GetType().GetMethod("DeriveParameters", BindingFlags.Static | BindingFlags.Public);

            method.Invoke(null, new object[] { cmd });
        }
示例#26
0
        DbCommandBuilder CreateCommandBuilder(string providerInvariantName)
        {
            DbConnection dbConn = this.Connection as DbConnection;

            DbProviderFactory factory = ((dbConn != null) ? DbProviderFactories.GetFactory(dbConn) : null)
                                        ?? GetProviderFactory(providerInvariantName);

            return(factory.CreateCommandBuilder());
        }
示例#27
0
        protected override void BeginProcessing()
        {
            var opener = new ConnectionSpecifier(FileOrName, Connection, null, null);

            _connection       = opener.Connection;
            _connectionOpened = opener.ConnectionOpened;

            try
            {
                if (_connection == null)
                {
                    WriteError(new ErrorRecord(new RuntimeException("Can't open a connection"), "", ErrorCategory.NotSpecified, null));
                    throw new PipelineStoppedException();
                }

                // ODBC and OLEDB Access connections fail to obtain the corresponding factories.
                if (_connection is System.Data.Odbc.OdbcConnection)
                {
                    _factory = DbProviderFactories.GetFactory("System.Data.Odbc");
                }
                else if (_connection is System.Data.OleDb.OleDbConnection)
                {
                    _factory = DbProviderFactories.GetFactory("System.Data.OleDb");
                }
                else
                {
                    _factory = DbProviderFactories.GetFactory(_connection);
                }

                if (_factory == null)
                {
                    WriteError(new ErrorRecord(new RuntimeException("Failed to obtain a DbProviderFactory object"), "", ErrorCategory.NotSpecified, null));
                    throw new PipelineStoppedException();
                }

                _builder = _factory.CreateCommandBuilder();

                // Supply a command builder with an adaptor object because some providers' builders
                // (including those of ODBC and OLEDB Access) require an active connection to make QuoteIndentifier() work.
                using (var adaptor = _factory.CreateDataAdapter())
                    using (var cmd = _connection.CreateCommand())
                    {
                        cmd.CommandText       = "select 1";
                        adaptor.SelectCommand = cmd;
                        _builder.DataAdapter  = adaptor;
                    }

                _useNamedParameters = false;
            }
            catch (Exception e)
            {
                DisposeResources();

                WriteError(new ErrorRecord(e, "", ErrorCategory.NotSpecified, null));
                throw new PipelineStoppedException();
            }
        }
示例#28
0
        void Initialize(string providerName, MetaModel mapping)
        {
            if (mapping == null)
            {
                Type thisType = GetType();

                if (thisType != typeof(Database))
                {
                    mapping = new AttributeMappingSource().GetModel(thisType);
                }
            }

            this.config = new DatabaseConfiguration(mapping);

            DbProviderFactory factory = this.Connection.GetProviderFactory();

            this.cb = factory.CreateCommandBuilder();

            this.config.LastInsertIdCommand   = "SELECT @@identity";
            this.config.DeleteConflictPolicy  = ConcurrencyConflictPolicy.IgnoreVersionAndLowerAffectedRecords;
            this.config.EnableBatchCommands   = true;
            this.config.EnableInsertRecursion = true;

            if (providerName != null)
            {
                string identityKey     = String.Format(CultureInfo.InvariantCulture, "DbExtensions:{0}:LastInsertIdCommand", providerName);
                string identitySetting = ConfigurationManager.AppSettings[identityKey];

                if (identitySetting != null)
                {
                    this.config.LastInsertIdCommand = identitySetting;
                }

                string batchKey     = String.Format(CultureInfo.InvariantCulture, "DbExtensions:{0}:EnableBatchCommands", providerName);
                string batchSetting = ConfigurationManager.AppSettings[batchKey];

                if (batchSetting != null)
                {
                    bool batch;

                    if (!Boolean.TryParse(batchSetting, out batch))
                    {
                        throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "The {0} appication setting must be a valid boolean.", batchSetting));
                    }

                    this.config.EnableBatchCommands = batch;
                }
            }

            if (mapping != null)
            {
                if (mapping.ProviderType == typeof(System.Data.Linq.SqlClient.Sql2008Provider))
                {
                    this.config.SqlDialect = SqlDialect.SqlServer2008;
                }
            }
        }
示例#29
0
        public DummyCommandBuilder(DbConnection connection)
        {
            DbProviderFactory  providerFactory = DbProviderFactories.GetFactory(connection);
            DbCommandBuilder   commandBuilder  = providerFactory.CreateCommandBuilder();
            Func <int, String> func            = GetParameterName;
            MethodInfo         methodInfo      = func.GetMethodInfo().GetBaseDefinition();

            _getParameterName = (Func <int, String>)Delegate.CreateDelegate(typeof(Func <int, String>), commandBuilder, methodInfo);
        }
示例#30
0
 public ReplicateToSqlIndexUpdateBatcher(
     DbProviderFactory providerFactory,
     string connectionString,
     IndexReplicationDestination destination)
 {
     _providerFactory  = providerFactory;
     _commandBuilder   = providerFactory.CreateCommandBuilder();
     _connectionString = connectionString;
     this.destination  = destination;
 }