public virtual void CloseFbData() { if (_con.State == ConnectionState.Open) { _con.Close(); _con.Dispose(); } }
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(); } }
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); } }
/// <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; } }
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); }
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); }
/// <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); }
/// <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); }
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(); }
public void Dispose() { if (OwnsConnection) { _connection.Dispose(); } }
public void Close() { if (fbConnection.State != System.Data.ConnectionState.Closed) { fbConnection.Close(); fbConnection.Dispose(); } }
public virtual void TearDown() { string cs = BuildConnectionString(FbServerType, Compression); _connection.Dispose(); DeleteAllData(cs); FbConnection.ClearAllPools(); }
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); } }
public void Dispose() { _conexao.Dispose(); if (_inTransacao) { _transacao.Dispose(); } }
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); }
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) { } }
public void Dispose() { if (!this.disposed) { conn.Dispose(); } this.disposed = true; GC.SuppressFinalize(this); }
public virtual void TearDown() { var cs = BuildConnectionString(FbServerType, Compression); _connection.Dispose(); if (_insertTestData) { DeleteAllData(cs); } FbConnection.ClearAllPools(); }
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(); }
public void Dispose() { if (connection != null) { if (connection.State == ConnectionState.Open) { connection.Close(); } connection.Dispose(); } }
/// <summary> /// Closes the connection. /// </summary> protected void CloseConnection() { if (_fbconnection?.State == ConnectionState.Open) { _fbconnection.Close(); } if (_fbconnection?.State == ConnectionState.Broken) { _fbconnection?.Dispose(); _fbconnection = null; } }
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); } }
/// <summary> /// 关闭数据库连接,如果有 /// </summary> public void Close() { if (cn == null) { return; } if (cn.State == ConnectionState.Open) { cn.Close(); } cn.Dispose(); }
public bool CloseConnection() { try { connection.Close(); connection.Dispose(); return(true); } catch (Exception) { return(false); } }
//----------------------------------------------------------------------------------------------------- public override void Dispose() { if (tr != null) { tr.Dispose(); tr = null; } if (db != null) { db.Dispose(); db = null; } }
// 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; }