About database connection

xiaoxiao2021-03-06  73

For the connection of the database, there are some common things; how many methods are accumulated, can be used as a multiplexed module. / ************************************************** ******************** JBFCMSConnect: import java.io. *; Import java.util. *; Import java.text. *; Import java.text. * Import java.lang. *;

/ ** * @author * * To change this generated comment edit the template variable "typecomment":. * Window> Preferences> Java> Templates * To enable and disable the creation of type comments go to * Window> Preferences> Java> Code . Generation * / public class JbfcmsConnect {private String drive = ""; private String dbURL = ""; private String prop_server_name = ""; private String prop_db_name = ""; private String dbUserName = ""; private String dbUserPassword = ""; Private string prop_db_provider; / ** * Onstructor for dbconnect * /

Public JBFCMSCONNECT () {init ();

. / ** * Method init * / private void init () {System.out.println ( "enter init"); Properties defaultSettings = new Properties (); defaultSettings.put ( "DB_NAME", "JBMMS"); defaultSettings. PUT ("DB_Provider", "DB2"); defaultsettings.put ("UserName", "root"); defaultsettings.put ("passwerd", "); defaultsettings.put (" driver_type "," net "); system .out.println ( "put default settings"); String prop_driver_type = defaultSettings.getProperty ( "DRIVER_TYPE"); prop_db_name = defaultSettings.getProperty ( "DB_NAME"); prop_db_provider = defaultSettings.getProperty ( "DB_PROVIDER"); dbUserName = defaultSettings. getProperty ( "USERNAME"); dbUserPassword = defaultSettings.getProperty ( "PASSWORD"); System.out.println ( "set default settings"); Properties settings = new Properties (); try {System.out.println ( "Start search Properties File "); FileInputStream sf = new FileInputStream (" c: //jbfcmsconnect.prop "); settings.load (sf); prop_driver_type = settings.getProperty (" DRIVER_TYPE "); prop_db_name = settings. getProperty ( "DB_NAME"); prop_db_provider = settings.getProperty ( "DB_PROVIDER"); dbUserName = settings.getProperty ( "USERNAME"); dbUserPassword = settings.getProperty ( "PASSWORD"); prop_server_name = settings.getProperty ( "SERVER_NAME") Sf.close (); System.out.Println ("Properties File Exist");

} catch (filenotfoundexception e) {system.out.println ("Properties File Was Not Found!");} catch (ioexception e) {system.out.println ("IOEXCEPTION IS FOUND!");} / if (Prop_DB_Provider. EqualsignoreCase ("DB2")) {if (Prop_Driver_type.equalsignorecase ("Net") {//system.Println ("Be in -----"); drive = "com.ibm.db2.jdbc. net.DB2Driver "; String prop_server_name = settings.getProperty (" SERVER_NAME "); dbURL =" jdbc: db2: // " prop_server_name " / " prop_db_name;} else {drive =" COM.ibm.db2.jdbc. App.db2driver "; dburl =" JDBC: DB2: " prop_db_name;} system.out.println (" DB2 Connection ==> / N DriverName = " DRIVE " / N URL = " DBURL " / N ") }

// MYSQL database connection else if (prop_db_provider.equalsIgnoreCase ( "mysql")) {if (prop_driver_type.equalsIgnoreCase ( "net")) {drive = "com.mysql.jdbc.Driver"; String prop_server_name = settings.getProperty ( " Server_name "); dburl =" jdbc: mysql: // " prop_server_name " / " prop_db_name;} else {drive =" com.mysql.jdbc.driver "; dburl =" JDBC: mysql: " prop_db_name;} System.out.println ("MySQL Connection ==> / N DriverName =" DRIVE "/ n");} // SQLServer database connection ELSE IF (Prop_DB_Provider.EqualsignoreCase ("SQLServer" )) {if (prop_driver_type.equalsIgnoreCase ( "net")) {drive = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; String prop_server_name = settings.getProperty ( "SERVER_NAME"); dbURL = "jdbc: microsoft: sqlserver: // " prop_server_name " / " prop_db_name;} else {drive =" com.microsoft.jdbc.sqlserver.SQLServerDriver "; dbURL =" jdbc: microsoft: sqlserver: // " prop_db_name;} System.out.println ("SQLServer Connection ==> / N DriverName =" Drive "/ n URL =" DBURL "/ N");}} connection conn = null; private Void connectpool () {try {class.forname (drive) .newinstance (); conn = drivermanager.getConnection (DBURL, DBUSERNAME, DBUSERPASSWORD);

} catch (classnotfoundexception EC) {system.out.println ("Database Drive Load Problem");} Catch (IllegaCcessException EI) {System.out.Println ("Database Access Exception");} catch (instantiationException EI) {system .out.println (Ei.getMessage ());} catch (sqlexception e) {system.out.println ("/ n ******************** * Database connection exception *********************** / N "); while (e! = Null) {system.out.println (" SQLState: " E.GETSQLSTATE ()); System.out.println ("Message:" E.GetMessage ()); System.out.Println ("vendor:" E.GETERRORCODE ()); E = E.GetNexTexception () ;}}} Public connection getConnect () {connectionPool (); Return Conn

}

} // This class is responsible for the connection section of the database: jbsqlexecute import java.io. *; Import java.util. *; Import java.util.date; import java.sql. *; Import java.text. *;

/ ** * @author * * To change this generated comment edit the template variable "typecomment":. * Window> Preferences> Java> Templates * To enable and disable the creation of type comments go to * Window> Preferences> Java> Code General Class JBSQLEXECUTE {

Private static connection con ===.ji;

/ ** * Constructor for jbsqlexecute. * / Public jbsqlexecute () {jBFcmsconnect connect = new jbfcmsconnect (); con = connect.getConnect ();

/ ** * Method sqlInsert * @param strInsert * @ * / public void sqlInsert (String strInsert) {try {pstmt = con.prepareStatement (strInsert);. Pstmt.execute ();} catch (SQLException sqle) {System.out .println ("JBMMS database insertion exception:" sqle.getMessage ());}

}

/ ** * Method strUpdata * @param strUpdata * @ * / public void sqlUpdata (String strUpdata) {try {pstmt = con.prepareStatement (strUpdata);. Pstmt.execute ();} catch (SQLException sqle) {System.out .println ("JBMMS database update exception:" SQLE.GetMessage ());}}

/ ** * Method Execute Query. * @Param strquery * @Return ResultSet * / public resultSet ExecuteQuery (string strquery) {resultset Rset = null; try {system.out.println (strQuery);

PSTMT = con?preparestatement (strquery); Rset = pstmt.executeQuery (); System.out.Println ("over");} catch (sqlexception sqle) {system.out.println ("JBMMS database query exception:" SQLE .getMessage ());} system.out.println ("rset"); Return Rset;}

/ ** * Method executeDelete * @param strDelete * / public void executeDelete (String strDelete) {try {pstmt = con.prepareStatement (strDelete);. Pstmt.execute ();} catch (SQLException sqle) {System.out.println ("JBMMS database delete exception:" sqle.getMessage ());}

}

/ / The execution of the database operation, call the method in such a class directly during use. / ************************************************** ***************** / A implementation of the database connection pool - Borrowing the user source code //ConnectionPool.java

Package com.abner.dbconnector;

Import java.sql. *;

Import java.util. *;

/ **

* The ConnectionPool class creates a connection pool that specifies a size for a specific database. Connection pool object

* Allows the client to specify the JDBC driver, database, username and password using the database. and,

* The client can specify the connection pool at the initial creation is the number of database connections, and the specified connection

* Not enough time automatically increase the number of connections and the number of database connections in the connection pool.

*

* External methods available: ConnectionPool: Constructor

* GetInitialConnections: Returns the connection pool initialization size

* SETINITIALCONNECONNECTIONS: Set the connection pool initialization size

* GetIncrementalConnections: Return to the increment of the connection pool

* SETINCREMENTALCONNECTIONS: Sets the size of the connection pool to add

* GetMaxConnections: Get the maximum allowable connection of the connection pool

* SetMaxConnections: Set the maximum allowable connection of the connection pool * GetTestTable: Get the name of the test table

* SettestTable: Set the name of the test table

* CreatePool: Create a connection pool, thread and synchronization

* getConnection: Get a database connection from the connection pool

* RETURNCONNECTION: Return to a connection to the connection pool

* Refreshconnections: Refreshing connection pool

* CloseConnectionPool: Close connection pool

*

* /

Public class connectionpool {

Private string jdbcdriver = ""; // database driver

Private string dburl = ""; // data URL

Private string dbusername = ""; // Database username

Private string dbpassword = ""; // Database User Password

Private string testtable = ""; // Test whether the connection available can be used, the default has no test table

Private int initialConnections = 10; // Connect the initial size of the pool

Private int incrementalconnections = 5; // Connection pool automatically increases

Private int maxConnections = 50; // Connect the largest size

Private Vector Connections = NULL; // Store vector of database connection in the connection pool, starting with NULL

// The object stored in it is the PooledConnection type

/ **

* Constructor

*

* @Param JDBCDriver String JDBC drive class string

* @Param DBURL STRING Database URL

* @Param DBUSERNAME STRING Connection Database User Name

* @Param DBPassword String Connection Database User's Password

*

* /

Public ConnectionPool (String JDBCDRIVER, STRING DBURL, STRING DBUSERNAME, STRING DBPASSWORD) {

this.jdbcdriver = jdbcdriver;

THIS.DBURL = DBURL;

THIS.DBUSERNAME = DBUSERNAME;

this.dbpassword = dbpassword;

}

/ **

* Returns the initial size of the connection pool

*

* @Return's number of connections available in the initial connection pool

* /

Public int GetinitialConnections () {

Return this.initialConnections;

}

/ **

* Set the initial size of the connection pool

*

* @PARAM is used to set the number of connections in the initial connection pool

* /

Public void setInitialconnections (int initialconnections) {

THIS.INITIALCONNECONNECONNES

}

/ **

* Returns the size of the connection pool to increase,

*

* @return connection pool automatically increases

* /

Public int getincrementalconnections () {

Return this.incrementalConnectAlConnection

}

/ **

* Set the size of the connection pool automatically increase

* @PARAM connection pool automatically increases the size

* /

Public void setincrementalconnections (int in inctribenterconnections) {

THIS.Incrementalconnections = incrementalConnections

}

/ **

* Returns the maximum number of available connections in the connection pool

* @return the maximum number of available connections in the connection pool

* /

Public int getmaxconnections () {

Return this.maxConnections;

}

/ **

* Set the maximum number of connections in the connection pool

*

* @PARAM Sets the maximum number of connections in the connection pool

* /

Public void setMaxConnections (int maxConnections) {

THIS.MAXCONNECTIONS = MAXCONNECTIONS;

}

/ **

* Get the name of the test database table

*

* @return test database table name

* /

Public string gettesttable () {

Return this.testtable;

}

/ **

* Set the name of the test table

* @Param TestTable String Test Table Name

* /

Public void settesttable (String TestTable) {

THIS.TESTTABLE = TESTTABLE;

}

/ **

*

* Create a database connection pool, using the number of available connections in the pool

* Settings set in InitialConnections

* /

Public synchronized void createpool () throws exception {

/ / Make sure the connection pool is not created

// If the connection pool is created, save the connection vector Connections will not empty

IF (Connections! = null) {

Return; // If you have been created, return

}

/ / Instantiate the driver instance specified in JDBC DRIVER

Driver Driver = (DRIVER) (this.jdbcdriver .newinstance ());

DriverManager.RegisterDriver (DRIVER); // Register a JDBC driver

// Create a saved vector, 0 elements are initially

CONNECTIONS = New Vector ();

/ / Create a connection according to the value set in InitialConnections.

CreateConnections (this.initialConnections);

System.out.println ("Database connection pool creation is successful!");

}

/ **

* Create a database connection specified by NumConnections and connect these connections

* Put in the Connections vector

*

* @Param NumConnections Number of database connections to be created

* /

Private Void CreateConnections (Int NumConnections) throws Sqlexception {

/ / Create a specified number of database connections

For (int x = 0; x

/ / Do you have the maximum number of database connections in the connection pool? Maximum value by class members MaxConnections

// Indicates that if MaxConnections is 0 or negative, it indicates that the number of connections is not limited.

// If the number of connections is maximized, you will exit.

IF (this.maxConnections> 0 && this.connections.size ()> = this.maxconnections) {Break;

}

// Add A New PooledConnection Object To Connections Vector

/ / Add a connection to the connection pool (vector Connections)

Try {

Connections.AddeElement (New PooledConnection);

} catch (sqlexception e) {

System.out.println ("Create Database Connection Failed!" E.GetMessage ());

Throw new sqlexception ();

}

System.out.println ("Database Connection is created ...");

}

}

/ **

* Create a new database connection and return it

*

* @Return returns a newly created database connection

* /

Private connection newconnection () throws sqlexception {

// Create a database connection

Connection conn = drivermanager.getConnection (DBURL, DBUSERNAME, DBPASSWORD);

// If this is the first time you create a database connection, you check the database, get this database to allow support.

// Maximum customer connection

//Connections.size ()==0 means that there is currently no connection to be created

IF (Connections.Size () == 0) {

DatabaseMetadata metadata = conn.getMetadata ();

INT drivermaxconnections = metadata.getmaxconnections ();

/ / DRIVERMAXCONNECTIONS returned by the database is 0, indicating that this database is not the biggest

// Connection restriction, or the maximum connection limit of the database does not know

// DriverMaxConnections is an integer returned, indicating that this database allows the number of clients to connect

/ / If the maximum number of connections set in the connection pool is greater than the number of connections allowed by the database, the maximum connection pool is set.

/ / The number of connections is the maximum number of databases allowed

IF (DriverMaxConnections> 0 && this.maxconnections> drivermaxconnections) {

THIS.MAXCONNECTIONS = DriverMaxConnections;

}

}

Return conn; // Return to the created new database connection

}

/ **

* Returns a available database connection by calling the getFreeConnection () function.

* If there is no database connection available, more database connections cannot be created

* Construction (such as the size of the connection pool size), this function will wait for a while to try it.

*

* @return Returns an available database connection object

* /

Public synchronized connection getConnection () throws sqlexception {

/ / Ensure that the connection pool is created

IF (Connections == Null) {

Return null; / / The connection pool is not created, then return NULL

}

Connection conn = getfreeConnection (); // Get an available database connection

// If there is no connection available, all the connections are in use while (conn == null) {

// Wait for a while

Wait (250);

Conn = getfreeConnection (); // Re-try until you get available connections, if

// getFreeConnection () Returns NULL

// indicates that it is not available after creating a batch of connections.

}

Return conn; // Returns the available connection

}

/ **

* This function returns an available database connection from the connection pool vector Connections, if

* There is currently no database connection available, this function is set according to IncrementalConnections

* The value creates several database connections and puts them in the connection pool.

* If you are created, all connections are still in use, return null

* @return Returns an available database connection

* /

Private connection getfreeConnection () throws sqlexception {

/ / A available database connection from the connection pool

Connection conn = findfreeConnection ();

IF (conn == null) {

// If there is no connection available in the current connection pool

// Create some connections

CreateConnections (INCREMENTALCONNECTIONS);

// Re-look for whether there is available connection

CONN = FINDFREECONNECTION ();

IF (conn == null) {

// Returns NULL if you still get available connections after creating a connection

Return NULL;

}

}

Return conn;

}

/ **

* Find all connections in the connection pool to find an available database connection,

* Returns NULL if there is no connection available

*

* @return Returns an available database connection

* /

PRIVATE Connection FindfreeConnection () throws sqlexception {

Connection conn = NULL;

PooledConnection PCONN = NULL;

// Get all objects in the connection pool vector

Enumeration enum = connections.efficient ();

// Traverse all objects to see if there is accessible connection

While (enum.hasmoreElements ()) {

PConn = (PooledConnection) enum.nexTelement ();

IF (! PConn.isbusy ()) {

// If this object is not busy, get its database connection and set it to busy

CONN = PCONN.GETCONNECTION ();

PConn.setbusy (TRUE);

// Test if this connection is available

IF (! TestConnection (conn) {

// If this connection is not available, create a new connection.

/ / Replace this unavailable connection object, if you fail, return null

Try {

CONN = NewConnection ();

} catch (sqlexception e) {

System.out.println ("Create Database Connection Failed!" E.GetMessage ());

Return NULL;

}

PCONN.SETCONNECTION (CONN);

}

Break; // Since finding an available connection, exit

}

}

Return conn; // Return to find available connection}

/ **

* Test if a connection is available, if you are not available, turn off it and return false

* Otherwise returns True

*

* @Param CONN needs to be tested database connection

* @return Returns True Indicates that this connection is available, FALSE is not available

* /

Private Boolean TestConnection (Connection CONN) {

Try {

/ / Judgment if the test form exists

IF (TestTable.equals (")) {

// If the test table is empty, try to use the setAutocommit () method of this connection

// To determine whether the connection is available (this method is only available in some databases, if not available,

// Throw an exception). Note: The method of using the test form is more reliable

Conn.setautocommit (TRUE);

} Else {// use test table test when there is a test form

// check if this connection is valid

Statement Stmt = conn.createstatement ();

Stmt.execute ("SELECT Count (*) from" TestTable);

}

} catch (sqlexception e) {

// Throw an exception, this connection is not available, turn it off, and return false;

CloseConnection (CONN);

Return False;

}

/ / Connection available, return true

Return True;

}

/ **

* This function returns a database to connect to the connection pool and set this connection to idle.

* All database connections available to the connection pool should be returned when not using this connection.

*

* @PARAM needs to return to the connection object in the connection pool

* /

Public void returnConnection (Connection CONN) {

/ / Make sure the connection pool exists, if the connection is not created (not existed), return directly

IF (Connections == Null) {

System.out.println ("Connecting pool does not exist, can not return this connection to the connection pool!");

Return;

}

PooledConnection PCONN = NULL;

Enumeration enum = connections.efficient ();

// Traverse all connections in the connection pool, find this connection object to return

While (enum.hasmoreElements ()) {

PConn = (PooledConnection) enum.nexTelement ();

// First find the connection object to be returned in the connection pool

IF (conn == pconn.getConnection ()) {

/ / Found, set this connection to idle state

PConn.setbusy (FALSE);

Break;

}

}

}

/ **

* Refresh all of the connection objects in the connection pool

*

* /

Public synchronized void refreshconnections () throws sqlexception {

/ / Ensure that the connection pool has an innovation

IF (Connections == Null) {

System.out.println ("Connecting the pool does not exist, no refresh!");

Return;

}

PooledConnection PCONN = NULL;

ENUMERATION ENUM = Connections.Elements (); while (enum.hasmorelements ()) {

// Get a connection object

PConn = (PooledConnection) enum.nexTelement ();

// If the object is busy, wait for 5 seconds, directly refreshed after 5 seconds

IF (PConn.isbusy ()) {

Wait (5000); // is 5 seconds

}

// Turn this connection, replace it with a new connection.

CloseConnection (PConn.getConnection ());

PCONN.SETCONNECTION (NewConnection ());

PConn.setbusy (FALSE);

}

}

/ **

* Turn off all connections in the connection pool and clear the pool.

* /

Public synchronized void closeconnectionpool () throws sqlexception {

/ / Make sure the connection pool exists, if there is no existence, return

IF (Connections == Null) {

System.out.println ("The connection pool does not exist, can't be turned off!");

Return;

}

PooledConnection PCONN = NULL;

Enumeration enum = connections.efficient ();

While (enum.hasmoreElements ()) {

PConn = (PooledConnection) enum.nexTelement ();

// If you are busy, wait for 5 seconds

IF (PConn.isbusy ()) {

Wait (5000); // is 5 seconds

}

// 5 seconds directly close it

CloseConnection (PConn.getConnection ());

// Remove it from the connection pool vector

Connections.RemoveElement (PCONN);

}

// Place the connection pool is empty

Connections = NULL;

}

/ **

* Close a database connection

*

* @PARAM needs to close database connection

* /

Private Void CloseConnection (Connection CONN) {

Try {

CONN.CLOSE ();

} catch (sqlexception e) {

System.out.println ("Close Database Connection Error:" E.GetMessage ());

}

}

/ **

* Make the program waiting for a given millisecond number

*

* @Param gives a number of milliseconds

* /

Private Void Wait (int mseconds) {

Try {

Thread.sleep (mseconds);

} catch (interruptedexception e) {

}

}

/ **

*

* Internal use of classes for saving connecting objects in the connection pool

* There are two members in this class, one is a database connection, and the other is to indicate if this connection is

* The logo is being used.

* /

Class pooledConnection {

Connection connection = null; // Database connection

Boolean busy = false; / / This connection is not using the flag, the default is not in use.

// Constructor, according to a connection to conscious a PooledConnection object

Public PooledConnection (Connection Connection) {

THIS.CONNECTION = Connection;

}

/ / Returns the connection in this object

Public connection getConnection () {

Return Connection;

}

// Set this object, connection

Public void setConnection (Connection Connection) {

THIS.CONNECTION = Connection;

}

// Get the object connection is busy

Public boolean isbusy () {

Return busy;

}

// Set the connection of the object is busy

Public void setbusy (boolean busy) {

THIS.BUSY = BUSY;

}

}

}

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

New Post(0)