예제 #1
0
 public virtual void CloseFbData()
 {
     if (_con.State == ConnectionState.Open)
     {
         _con.Close();
         _con.Dispose();
     }
 }
예제 #2
0
        public static bool check_func(FbConnectionStringBuilder fc)
        {
            bool res_ = false;

            using (FbConnection fb = new FbConnection(fc.ConnectionString))
            {
                try
                {
                    fb.Open();
                    using (FbTransaction ft = fb.BeginTransaction())
                    {
                        using (FbCommand fcon = new FbCommand(sql_func, fb, ft))
                        {
                            using (FbDataReader fr = fcon.ExecuteReader())
                            {
                                while (fr.Read())
                                {
                                    res_ = true;
                                }
                                fr.Dispose();
                            }
                            fcon.Dispose();
                        }
                        ft.Commit();
                        ft.Dispose();
                    }
                }
                catch { }
                finally { fb.Close(); }
                fb.Dispose();
            }
            return(res_);
        }
 public void Dispose()
 {
     if (sqlConnection != null)
     {
         sqlConnection.Dispose();
     }
 }
예제 #4
0
 public Boolean delete(DateTime date1, string prodavec)
 {
     try
     {
         check deletingCheck = this.Where(x => x.date == date1 && x.prodavec == prodavec).FirstOrDefault();
         if (deletingCheck == null)
         {
             return(false);
         }
         FbConnection fb = new FbConnection(connection.connectionString());
         fb.Open();
         FbTransaction fbt       = fb.BeginTransaction(); //стартуем транзакцию; стартовать транзакцию можно только для открытой базы (т.е. мутод Open() уже был вызван ранее, иначе ошибка)
         FbCommand     SelectSQL = new FbCommand();
         SelectSQL.CommandText = "update shopheads set closed=1 where saledate=@datetime and saler=@prodavec";
         SelectSQL.Parameters.Add("@datetime", date1);
         SelectSQL.Parameters.Add("@prodavec", deletingCheck.prodavecCode);
         SelectSQL.Connection  = fb;
         SelectSQL.Transaction = fbt;
         SelectSQL.ExecuteNonQuery();
         fbt.Commit();
         fb.Close();
         SelectSQL.Dispose(); //в документации написано, что ОЧЕНЬ рекомендуется убивать объекты этого типа, если они больше не нужны
         fbt.Dispose();
         fb.Dispose();
         this.Remove(deletingCheck);
         return(true);
     }
     catch (Exception e)
     {
         return(false);
     }
 }
예제 #5
0
        /// <summary>
        /// ExecuteReader方法
        /// </summary>
        /// <param name="sql">Sql语句</param>
        /// <param name="type">命令类型</param>
        /// <param name="args">参数</param>
        /// <returns>DataReader对象</returns>
        private IDataReader ExecuteReader(string sql, CommandType type, params IDbDataParameter[] args)
        {
            #region # 验证参数

            if (string.IsNullOrWhiteSpace(sql))
            {
                throw new ArgumentNullException(nameof(sql), @"SQL语句不可为空!");
            }

            #endregion

            FbConnection conn = this.CreateConnection();
            try
            {
                FbCommand cmd = new FbCommand(sql, conn)
                {
                    CommandType = type
                };
                cmd.Parameters.AddRange(args);
                conn.Open();
                return(cmd.ExecuteReader(CommandBehavior.CloseConnection));
            }
            catch
            {
                conn.Dispose();
                throw;
            }
        }
예제 #6
0
        public static DataTable GenericSelect(string sql, string connectionstring)
        {
            FbConnection  cn     = null;
            FbCommand     cmd    = null;
            DataSet       ds     = new DataSet();
            FbDataAdapter da     = null;
            DataTable     result = null;

            try
            {
                cn = new FbConnection(connectionstring);
                cn.Open();
                cmd = new FbCommand(sql, cn);
                da  = new FbDataAdapter(cmd);
                da.Fill(ds);
                result = ds.Tables[0];
            }
            catch (FbException ex)
            {
                ExceptionHelper.Log(ex);
            }
            finally {
                da.Dispose();
                cmd.Dispose();
                cn.Dispose();
            }

            //handle nulls?
            return(result);
        }
예제 #7
0
        public static bool GenericCommand(string sql, string connectionstring)
        {
            FbConnection cn     = null;
            FbCommand    cmd    = null;
            var          result = false;

            try
            {
                cn = new FbConnection(connectionstring);
                cn.Open();
                cmd = new FbCommand(sql, cn);
                cmd.ExecuteNonQuery();

                result = true;
            }
            catch (FbException ex)
            {
                ExceptionHelper.Log(ex);
            }
            finally
            {
                cmd.Dispose();
                cn.Dispose();
            }

            //handle nulls?
            return(result);
        }
예제 #8
0
        /// <summary>
        /// Makes a physical connection and tests that the storage is ready to use
        /// </summary>
        /// <param name="connectionString">connection string</param>
        /// <param name="resultMessage">Message returned from server when connection test complete</param>
        /// <returns>true if all ok, otherwise false</returns>
        private bool ConnectFirebird(string connectionString, ref string resultMessage)
        {
            bool Result = false;

            FbConnection db = new FbConnection(connectionString);

            try
            {
                db.Open();
                resultMessage = String.Format("OK - Server Version: {0}", db.ServerVersion);

                Result = true;
            }
            catch (Exception error)
            {
                Shared.EventLog.Add(error);
                resultMessage = error.Message;
                Result        = false;
            }
            finally
            {
                db.Close();
                db.Dispose();
                db = null;
            }

            return(Result);
        }
예제 #9
0
        /// <summary>
        /// Create a connection to the Firebird database
        /// </summary>
        /// <returns>The created <see cref="FbConnection"/></returns>
        ///
        /// <exception cref="ConnectionException">
        /// If a connection to the database could not be established.
        /// </exception>
        public override FbConnection CreateConnection()
        {
            logger.LoggingWrapper(() =>
            {
                // Build the connection string
                var connectionString = base.connectionString +
                                       "Dialect=3;" +
                                       "Charset=NONE;" +
                                       "Role=;" +
                                       "Connection lifetime=15;" +
                                       "Pooling=true;" +
                                       "MinPoolSize=0;" +
                                       "MaxPoolSize=50;" +
                                       "Packet Size=8192;" +
                                       "ServerType=0";

                try
                {
                    connection = new FbConnection(connectionString);
                    connection.Open();
                }
                catch (Exception ex)
                {
                    connection.Dispose();
                    throw new ConnectionException(ex.Message, ex.InnerException);
                }
            });

            return(connection);
        }
예제 #10
0
        private void DisposeAll()
        {
            //Prevent Dispos if have transaction
            if (_tran != null && _tran.Connection != null)
            {
                return;
            }

            if (_tran != null)
            {
                _tran.Dispose();
                _tran = null;
            }


            if (_com != null)
            {
                _com.Dispose();
                _com = null;
            }

            if (_con != null)
            {
                _con.Dispose();
                _con = null;
            }


            if (_adapter != null)
            {
                _adapter.Dispose();
                _adapter = null;
            }
        }
        public virtual void TearDown()
        {
            string cs = BuildConnectionString(_fbServerType);

            if (_withTransaction)
            {
                try
                {
                    if (!_transaction.IsUpdated)
                    {
                        _transaction.Commit();
                    }
                }
                catch
                {
                }
                try
                {
                    _transaction.Dispose();
                }
                catch
                {
                }
            }
            if (_connection != null)
            {
                _connection.Dispose();
            }
            DeleteAllData(cs);
            FbConnection.ClearAllPools();
        }
예제 #12
0
 public void Dispose()
 {
     if (OwnsConnection)
     {
         _connection.Dispose();
     }
 }
예제 #13
0
 public void Close()
 {
     if (fbConnection.State != System.Data.ConnectionState.Closed)
     {
         fbConnection.Close();
         fbConnection.Dispose();
     }
 }
예제 #14
0
        public virtual void TearDown()
        {
            string cs = BuildConnectionString(FbServerType, Compression);

            _connection.Dispose();
            DeleteAllData(cs);
            FbConnection.ClearAllPools();
        }
예제 #15
0
 public void Open()//打开连接
 {
     try
     {
         if (DBConnection != null && DBConnection.State != ConnectionState.Closed)
         {
             DBConnection.Close();
             DBConnection.Dispose();
         }
         DBConnection = new FbConnection(GetConnstr());
         DBConnection.Open();
     }
     catch (Exception ex)
     {
         throw new Exception("打开数据库失败,错误信息:" + ex.Message);
     }
 }
예제 #16
0
 public void Dispose()
 {
     _conexao.Dispose();
     if (_inTransacao)
     {
         _transacao.Dispose();
     }
 }
예제 #17
0
 public void Dispose()
 {
     if (connection != null)
     {
         connection.Dispose();
     }
     GC.SuppressFinalize(this);
 }
        /// <summary>
        /// Creates new replication triggers based on rules in REPLICATE$TABLES
        /// </summary>
        public bool PrepareDatabaseForReplication(string connectionString,
                                                  bool dbUpdated, bool generateOnly, ref string fileName, DatabaseRemoteUpdate remoteUpdate)
        {
            bool Result = false;

            try
            {
                _xmlHashUpdates.Clear();

                FbConnection localDB = new FbConnection(connectionString);
                try
                {
                    localDB.Open();

                    if (dbUpdated)
                    {
                        Shared.EventLog.Add("Rebuilding Replication Triggers");
                        fileName = RebuildReplicationTriggers(connectionString, generateOnly);
                        bool tableUpdated = false;

                        if (generateOnly)
                        {
                            return(true);
                        }

                        if (remoteUpdate.UpdateDatabase(connectionString, fileName, -1, ref tableUpdated))
                        {
                            File.Delete(fileName);

                            foreach (string update in _xmlHashUpdates)
                            {
                                string[] parts = update.Split('$');

                                Shared.XML.SetXMLValue(parts[0], parts[1], parts[2]);
                            }
                        }
                        else
                        {
                            throw new Exception("Error creating replication triggers");
                        }

                        Result = true;
                    }
                }
                finally
                {
                    localDB.Dispose();
                    localDB = null;
                }
            }
            catch (Exception err)
            {
                Shared.EventLog.Add(err);
            }

            return(Result);
        }
예제 #19
0
        public void get()
        {
            try
            {
                FbConnection fb = new FbConnection(connection.connectionString());
                fb.Open();
                FbTransaction fbt       = fb.BeginTransaction();                                                                                                                                                                                                                                                                                                                                                                                             //стартуем транзакцию; стартовать транзакцию можно только для открытой базы (т.е. мутод Open() уже был вызван ранее, иначе ошибка)
                FbCommand     SelectSQL = new FbCommand();
                SelectSQL.CommandText = "select a.saledate,c.fullname,d.shortname,coalesce((select sum(b.price * b.quanshop) as summ from shoplog b where b.datatime = a.saledate and b.staff_id = a.saler group by datatime, staff_id),0) as summ, a.saler,a.closed,c.inn,(c.fam || ' ' || c.im || ' ' || c.otch ) as fn FROM shopheads a join staff c on c.id = a.saler left join pokupat d  on a.pokupatid = d.pokupatcode where a.saledate > @datetime"; //задаем запрос на выборку
                SelectSQL.Parameters.Add("@datetime", DateTime.Now.Date);
                SelectSQL.Connection  = fb;
                SelectSQL.Transaction = fbt;                     //необходимо проинициализить транзакцию для объекта SelectSQL
                FbDataReader reader = SelectSQL.ExecuteReader(); //для запросов, которые возвращают результат в виде набора данных надо использоваться метод ExecuteReader()

                try
                {
                    while (reader.Read()) //пока не прочли все данные выполняем...
                    {
                        var d1  = reader.GetDateTime(0);
                        var d2  = reader.GetString(1);
                        var d3  = reader.GetString(2);
                        var d4  = reader.GetDouble(3);
                        var d5  = reader.GetInt16(4);
                        var d6  = reader.GetString(6);
                        var d7  = reader.GetString(7);
                        var nch = new check(d1, d2, d3, d4, d5, d6, d7);
                        var j   = reader.GetInt16(5);
                        if (reader.GetInt16(5) == 0)
                        {
                            if (this.Where(x => x.date == nch.date && x.prodavec == nch.prodavec).Count() == 0)
                            {
                                this.Add(nch);
                            }
                        }
                        else
                        {
                            var dch = this.Where(x => x.date == nch.date && x.prodavec == nch.prodavec).FirstOrDefault();
                            if (dch != null)
                            {
                                this.Remove(dch);
                            }
                        }
                    }
                }
                finally
                {
                    //всегда необходимо вызывать метод Close(), когда чтение данных завершено
                    reader.Close();
                    fbt.Commit();
                    fb.Close();      //закрываем соединение, т.к. оно нам больше не нужно
                }
                SelectSQL.Dispose(); //в документации написано, что ОЧЕНЬ рекомендуется убивать объекты этого типа, если они больше не нужны
                fbt.Dispose();
                fb.Dispose();
            }
            catch (Exception e) { }
        }
예제 #20
0
 public void Dispose()
 {
     if (!this.disposed)
     {
         conn.Dispose();
     }
     this.disposed = true;
     GC.SuppressFinalize(this);
 }
예제 #21
0
        public virtual void TearDown()
        {
            var cs = BuildConnectionString(FbServerType, Compression);

            _connection.Dispose();
            if (_insertTestData)
            {
                DeleteAllData(cs);
            }
            FbConnection.ClearAllPools();
        }
예제 #22
0
        public void Dispose()
        {
            if (Conn.State != ConnectionState.Closed)
            {
                Conn.Close();
                Conn.Dispose();
                Conn = null;
            }

            GC.SuppressFinalize(this);
        }
        public virtual async Task TearDown()
        {
            var cs = BuildConnectionString(ServerType, Compression, WireCrypt);

            _connection.Dispose();
            if (_insertTestData)
            {
                await DeleteAllData(cs);
            }
            FbConnection.ClearAllPools();
        }
예제 #24
0
 public void Dispose()
 {
     if (connection != null)
     {
         if (connection.State == ConnectionState.Open)
         {
             connection.Close();
         }
         connection.Dispose();
     }
 }
예제 #25
0
 /// <summary>
 /// Closes the connection.
 /// </summary>
 protected void CloseConnection()
 {
     if (_fbconnection?.State == ConnectionState.Open)
     {
         _fbconnection.Close();
     }
     if (_fbconnection?.State == ConnectionState.Broken)
     {
         _fbconnection?.Dispose();
         _fbconnection = null;
     }
 }
예제 #26
0
 protected bool Desconectar()
 {
     try
     {
         if (fbConnection.State != ConnectionState.Closed)
         {
             fbConnection.Close();
             fbConnection.Dispose();
             return(true);
         }
         else
         {
             fbConnection.Dispose();
             return(false);
         }
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
예제 #27
0
 /// <summary>
 /// 关闭数据库连接,如果有
 /// </summary>
 public void Close()
 {
     if (cn == null)
     {
         return;
     }
     if (cn.State == ConnectionState.Open)
     {
         cn.Close();
     }
     cn.Dispose();
 }
예제 #28
0
 public bool CloseConnection()
 {
     try
     {
         connection.Close();
         connection.Dispose();
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
예제 #29
0
        //-----------------------------------------------------------------------------------------------------

        public override void Dispose()
        {
            if (tr != null)
            {
                tr.Dispose();
                tr = null;
            }
            if (db != null)
            {
                db.Dispose();
                db = null;
            }
        }
예제 #30
0
 // IDisposable
 protected virtual void Dispose(bool pDisposing)
 {
     if (!this.disposedValue)
     {
         if (pDisposing)
         {
             // TODO: eliminar estado administrado (objetos administrados).
         }
         // TODO: liberar recursos no administrados (objetos no administrados) e invalidar Finalize() below.
         // TODO: Establecer campos grandes como Null.
         _conexion.Dispose();
         //ClearMemory();
     }
     this.disposedValue = true;
 }