Database Connectivity

xiaoxiao2021-03-06  22

Database Connectivity

Most database interfaces depends on some database connection objects, which seem to be bridge between application code and database. Typically, a connection must be opened until the database operation command is executed. In fact, a display connection is often required to establish and execute commands. During the entire process executed by the command, the connection must be open, the result of the query will return a recordset, and turn off the database connection. If you are running in a transaction, you often bind your transaction on a specific connection. When it is running, this connection must always be opened until this transaction ends to close the connection.

In many environments, the overhead of establishing a connection is quite large, which requires a connection pool. In this case, the developer requests a connection to the connecting pool and releases after completion without instant creation and closing. Note that this is not to create a connection pool, because most platforms provide a connection pool, so you rarely need to implement the connection pool. If you have to implement the connection pool yourself, you must first check that the connection pool is really improved (the creation of the connection pool can be referred to the code [1]). Also note: More and more environments allow us to create new connections faster, so you don't need to use buffer pools.

The environment that provides the connection pool puts the connection pool behind a similar to create a new connection interface. With this method, you don't have to know if you get a new creation connection or allocated from the connection pool. Similarly, close a connection may not really turn off it, but just replace it to get and release from the connection pool.

Whether the cost of creating a connection is high or low, the connection must be managed because they are precious resources, they must be closed immediately. Also, if you are ongoing a transaction, you usually need to guarantee: In this particular transaction, each command is sent from the same connection.

The most common recommendation is to use one to the connection pool or the connection manager, display a connection, and through it to execute the database command, once the execution is performed, immediately turn it off. This proposal has brought two questions: First, ensure a connection can be obtained in any place; second, it is ensured that it will not be closed at the end (can be referred to the sample code [2]).

The modern environment provides an automatic memory management and garbage collection mechanism, so that a way to ensure connection is to use garbage collectors. In this manner, the object that is connected itself or references this connection will close the connection during garbage collection. The benefits of this are: it uses the same mechanism as memory management, which is equally convenient, and is not strange. The problem is that the connection is closed only when the garbage collector actually recovers memory, may have lost its last reference for this connection for a long time, the result is that the connection that is not referenced may be separated for a while. is closed. Overall, I don't like to rely on garbage collection mechanisms, and even other mechanisms, even display closing will be better. Of course, the garbage collection mechanism is still a good backup in the event of other mechanisms.

Connection management details Description are often characteristics of database interaction software, so the policies used are usually determined by the environment.

Create sample code for connecting pools [1]:

Using system;

Using system.timers;

Using system.collections;

Using system.data.sqlclient;

USING COMMON;

Namespace SQLDBConnection

{

///

/// DBConnection database connection target pool.

///

Public Sealed Class Dbconnection: ObjectPool

{

Private dbconnection ()

{

}

Public static readonly dbconnection instance = new dbconnection (); private static string _connectionstring = "Database connection string";

Public Static String Connectionstring

{

set

{

_Connectionstring = Value;

}

get

{

Return_ConnectionString;

}

}

Protected Override Object Create ()

{

Try

{

SqlConnection Temp = New SQLCONNECTION (_Connectionstring);

Temp.open ();

Return (TEMP);

}

Catch

{

Return NULL;

}

}

Protected Override Bool Validate (Object O)

{

Try

{

SqlConnection Temp = (SqlConnection) O;

return (((temp.State.Equals (System.Data.ConnectionState.Closed)))!);

}

Catch (SQLException)

{

Return False;

}

}

Protected Override Void Expire (Object O)

{

Try

{

(SqlConnection) o) .Close ();

}

Catch (SQLException)

{

}

}

Public SqlConnection BorrowDbConnection ()

{

Try

{

Return ((SqlConnection) Base.GetObjectFromPool ());

}

Catch (Exception E)

{

Throw e;

}

}

Public Void ReturndbConnection (SqlConnection C)

{

Base.ReturnObjectTopool (C);

}

}

///

/// ObjectPool object pool.

///

Public Abstract Class ObjectPool

{

PRIVATE long_lastcheckout;

Private static hashtable lock;

Private static hashtable unlocked;

INTERNAL Static long carbage_interval = 9 * 1000;

Static ObjectPool ()

{

Locked = Hashtable.Synchronized (new hashtable ());

Unlocked = hashtable.synchronized (new hashtable ());

}

Internal ObjectPool ()

{

_LastCheckout = datetime.now.ticks;

System.timers.timer atimer = new system.timers.timer ();

atim.enabled = true;

atimer.interval = carbage_interval;

Atimer.ELAPSED = New System.Timers.ELAPSEDEVENTHANDLER (Collectgarbage);

}

Protected abstract object crete ();

Protected Abstract Bool Validate (Object O);

Protected Abstract Void Expire (Object O); Internal Object GetObjectFromPool ()

{

Long now = datetime.now.ticks;

_LastCheckout = now;

Object o = NULL;

o = crete ();

Locked.Add (o, now);

Return (O);

}

Internal Void ReturnObjectTopool (Object O)

{

IF (o! = null)

{

LOCK (this)

{

Locked.Remove (O);

Unlocked.Add (o, datetime.now.ticks);

}

}

}

Private void Collectgarbage (Object Sender, System.Timers.ELAPSEDEventArgs EA)

{

LOCK (this)

{

Object O;

Long now = datetime.now.ticks;

IDictionaryEnumerator E = unlocked.GeteNumerator ();

Try

{

While (E.MOVENEXT ())

{

o = E.KEY;

IF ((NOW - UNLOCKED [O])> CARBAGE_INTERVAL)

{

UNLOCKED.REMOVE (O);

Expire (O);

o = NULL;

}

}

}

Catch (Exception) {}

}

}

}

}

Database connection sample code [2]:

Using system;

Using system.data;

Using system.data.sqlclient;

Using system.configuration;

Using SqldbConnection;

USING COMMON;

Namespace MyMedia_competitor

{

///

/// SQLDATABASE's summary description.

///

Public Class MySQLDATABASE

{

///

/// Constructor

///

Public mysqldatabase ()

{

}

Public DBConnection Connection;

///

/// Get database connection interface

///

Public IDBConnection getConnection ()

{

IDBCONNECTION SQLCONNECTION1 = NULL;

String Connectionstring = "Database Connection String";

SqlConnection1 = (IDBConnection) New SqlConnection (Connectionstring);

SqlConnection1.open ();

Return SqlConnection1;

}

///

/// Return the database connection interface to the connection pool

///

Public void returnnection (SqlConnection Obj)

{

Connection.ReturndbConnection (OBJ);

}

///

/ / Obtain the database command interface according to the database type

///

/// Database command string

/// Database connection interface /// database command interface

///

Private idbcommand getcommand (String Sqlstr, IDBConnection SqlConnection1)

{

IDBCommand Sqlcommand1 = NULL;

SQLCOMMAND1 = New SQLCOMMAND (Sqlstr, (SqlConnection) SQLCONNECTION1);

Sqlcommand1.commandtimeout = 9999999;

Return Sqlcommand1;

}

///

/ / Obtain the data adapter interface according to the database type

/// Database command interface

/// Data Adapter Interface

Private iDataAdapter getDataAdapter (idbcommand sqlcommand1)

{

IDataAdapter SqldataAdapter1 = NULL;

SqlDataAdapter1 = new SqlDataAdapter ((SQLCommand) SQLCommand1);

DataAdapte = SqlDataAdapter1;

Return SqldataAdapter1;

}

///

/// data adapter properties

///

IDataAdapter DataAdapte = NULL;

Private iDataAdapter DataAdapter

{

get

{

Return DataAdapte;

}

}

///

/// below is processing data, return result set

///

// 1.

///

/ / Operate the SQL statement and return the number of affected rows

/// Database command string

/// Number of affected rows

///

Public Int ExecutenonQuery (String SQLSTR)

{

IDBCONNECTION SQLCONNECTION1 = NULL;

IDBCommand Sqlcommand1 = NULL;

Try

{

SqlConnection1 = this.getConnection ();

SQLCommand1 = this.getCommand (Sqlstr, SqlConnection1);

Return Sqlcommand1.executenonQuery ();

}

Catch (Exception EX)

{

System.Diagnostics.debug.writeLine (ex.Message);

Return 0;

}

Finally

{

IF (SQLCommand1! = NULL)

Sqlcommand1.dispose ();

IF (SqlConnection1! = NULL)

SqlConnection1.close ();

// connection.returndbconnection (SqlConnection) SqlConnection1);

}

// 2.

///

/ / / Execute the SQL statement and return to the data line

/// Database command string

/// Data reader interface

///

Public SqlDataReader ExecuteReader (String SQLSTR)

{

IDBCONNECTION SQLCONNECTION1 = NULL;

IDBCommand Sqlcommand1 = NULL;

Try

{

SqlConnection1 = this.getConnection ();

SQLCommand1 = this.getCommand (Sqlstr, SqlConnection1);

Return (SqlDataReader) sqlcommand1.executeReader (Commandbehavior.CloseConne);

}

Catch (Exception EX)

{

System.Diagnostics.debug.writeLine (ex.Message);

Return NULL;

}

Finally

{

IF (SQLCommand1! = NULL)

Sqlcommand1.dispose ();

IF (SqlConnection1! = NULL)

SqlConnection1.close ();

// Connection.ReturndbConnection (SqlConnection) SQLConnection1);

}

}

// 3.

///

/ / / Execute the SQL statement and return a single value object

// / The first data of the first line of the result

/// Database command string

/// single-value object - Results The first data of the first line of the column

///

Public Object ExecuteScalar (String SQLSTR)

{

IDBCONNECTION SQLCONNECTION1 = NULL;

IDBCommand Sqlcommand1 = NULL;

Try

{

SqlConnection1 = this.getConnection ();

SQLCommand1 = this.getCommand (Sqlstr, SqlConnection1);

Return Sqlcommand1.executescalar ();

}

Catch (Exception EX)

{

System.Diagnostics.debug.writeLine (ex.Message);

Return NULL;

}

Finally

{

IF (SQLCommand1! = NULL)

Sqlcommand1.dispose ();

IF (SqlConnection1! = NULL)

SqlConnection1.close ();

// Connection.ReturndbConnection (SqlConnection) SQLConnection1);

}

}

// 4.

///

// / Pack a dataset object and return it

/// Database command string /// Data selection object

///

Public Dataset getDataSet (String SQLSTR)

{

IDBCONNECTION SQLCONNECTION1 = NULL;

IDBCommand Sqlcommand1 = NULL;

IDataAdapter SqldataAdapter1 = NULL;

DataSet DS = NULL;

Try

{

SqlConnection1 = this.getConnection ();

SQLCommand1 = this.getCommand (Sqlstr, SqlConnection1);

Sqldataadapter1 = this.getdataadapter (SqlCommand1);

DS = new dataset ();

SqlDataAdapter1.fill (DS);

Return DS;

}

Catch (Exception EX)

{

System.Diagnostics.debug.writeLine (ex.Message);

Return NULL;

}

Finally

{

IF (SQLCommand1! = NULL)

Sqlcommand1.dispose ();

IF (SqlConnection1! = NULL)

SqlConnection1.close ();

//Connection.ReturndbConnection ((SqlConnection )SqlConnection1);

}

}

//5.

///

/// Execute a stored procedure

/// Store process name

/// The parameter to be incorporated

/// Data set object

///

Public DataSet getDataSetForstored (String StoredStr, Sqlparameter [] Arrparams)

{

IDBCONNECTION SQLCONNECTION1 = NULL;

IDBCommand Sqlcommand1 = NULL;

IDataAdapter SqldataAdapter1 = NULL;

DataSet DS = NULL;

Try

{

SqlConnection1 = this.getConnection ();

SQLCommand1 = this.getCommand (StoredStr, SqlConnection1);

Sqlcommand1.commandtype = commandtype.storedProcedure;

For (int i = 0; I

{

Sqlcommand1.parameters.add (arrparams [i]);

}

Sqldataadapter1 = this.getdataadapter (SqlCommand1);

DS = new dataset ();

SqlDataAdapter1.fill (DS);

Return DS;

}

Catch (Exception EX)

{

System.Diagnostics.debug.writeline; Return NULL;

}

Finally

{

IF (SQLCommand1! = NULL)

Sqlcommand1.dispose ();

IF (SqlConnection1! = NULL)

SqlConnection1.close ();

// Connection.ReturndbConnection (SqlConnection) SQLConnection1);

}

}

//6.

///

/// Execute a stored procedure

/// Store process name

/// The parameter to be incorporated

/// Data set object

///

Public void Runstored (String StoredStr, Sqlparameter [] Arrparams)

{

IDBCONNECTION SQLCONNECTION1 = NULL;

IDBCommand Sqlcommand1 = NULL;

Try

{

SqlConnection1 = this.getConnection ();

SQLCommand1 = this.getCommand (StoredStr, SqlConnection1);

Sqlcommand1.commandtype = commandtype.storedProcedure;

For (int i = 0; I

{

Sqlcommand1.parameters.add (arrparams [i]);

}

Sqlcommand1.executenonQuery ();

}

Catch (Exception EX)

{

System.Diagnostics.debug.writeLine (ex.Message);

}

Finally

{

IF (SQLCommand1! = NULL)

Sqlcommand1.dispose ();

IF (SqlConnection1! = NULL)

SqlConnection1.close ();

//Connection.ReturndbConnection ((SqlConnection )SqlConnection1);

}

}

///

/// can continue to expand

///

Writer: phoenix liu

MSN: Phoenix_6@hotmail.com.cn

Time: 2005-3-31

转载请注明原文地址:https://www.9cbs.com/read-40596.html

New Post(0)