⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 databasehelper.java

📁 Sun公司Dream项目
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        try {

	        Class.forName(m_databaseDriver).newInstance();

         } catch (InstantiationException e) {

             m_initError = true;

             m_log.severe("JDBC Driver can not be instantiated [" + e.getMessage() + "]");

             e.printStackTrace();

	     } catch (IllegalAccessException e) {

             m_initError = true;

             m_log.severe("Illegal access exception thrown while instantiating the JDBC driver [" + e.getMessage() + "]");

             e.printStackTrace();

	     } catch (ClassNotFoundException e) {

             m_initError = true;

             m_log.severe("JDBC Driver is not in the classpath at the runtime [" + e.getMessage() + "]");

	         e.printStackTrace();

	     }

         m_log.finer("Leaving Function...");

    }



	

    /**

     * Get the values of databaseDriver, databaseURL, username and password.

     * @param XML Document data structure containing the configuration file. 

     */

    private void initializeProperties(Document doc) {

        m_log.finer("Entering Function...");

        m_databaseDriver = getConfParameterValue(doc, "drivername");

        m_databaseURL = getConfParameterValue(doc, "databaseurl");

        m_databaseUser = getConfParameterValue(doc, "username");

        m_databasePassword = getConfParameterValue(doc, "password");

        m_listTableSql = getConfParameterValue(doc, "listTableSql");

        String tableColumnNumber = getConfParameterValue(doc, "tableNameColumnNumber");

        m_tableColumnNumber = Integer.parseInt(tableColumnNumber);

        m_log.finer("Leaving Function...");

    }

    

    /**

     * Gets the value of configuration parameters specified in configuration file.

     * @param Configuration file as a XML Document object.

     * @param Configuration parameter

     */

    String getConfParameterValue(Document doc, String confParameter) {

        m_log.finer("Entering Function...");

        NodeList tempNodeList = null;

        String value = null;

        tempNodeList = doc.getElementsByTagName(confParameter);

        if (tempNodeList == null) {

            m_log.severe("Value of parameter [" + confParameter + "] is null");

        	return null;

        }

        if (tempNodeList.item(0) == null) {

            m_log.severe("Value of parameter [" + confParameter + "] is null");

            return null;   

        }

        if (tempNodeList.item(0).getFirstChild() == null) {

            m_log.severe("Value of parameter [" + confParameter + "] is null");

            return null;   

        }

        value = tempNodeList.item(0).getFirstChild().getNodeValue();

        m_log.fine("Value of parameter [" + confParameter + "] is [" + value + "]");

        m_log.finer("Leaving Function...");

        return value;

    }

 

    /**

     * getDatabaseHelper is used to get the sole instance of DatabaseHelper.

     * @param  ServletContext used to obtain a handle to the database configuration file.

     * @return The sole instance of DatabaseHelper class.

     */

    public static DatabaseHelper  getDatabaseHelper()

    throws LicenseServerException {

        m_log.finer("Entering Function...");

        if (m_databaseHelper == null) {

           m_log.severe("getDatabaseHelper is being called without calling init(..) first"); 

           throw new LicenseServerException(LicenseServerException.EC_NO_ERROR_CODE, 

                                            "getDatabaseHelper is being called without calling init(..) first");

        }

        return m_databaseHelper;

    }

    

    /**

     * Execute a sql statement which does not returns value

     * @param sql statement

     * @return number of rows affected by the statement

     */

    public int executeStatementWithoutResults(String s) 

    throws LicenseServerException {

        m_log.finer("Entering Function...");

        m_log.fine("Going to execute statement [" + s + "] that produces no results.");

        int          count = 0;

        Connection   con = getConnection();

        Statement    st = null;

		try {

			st    = con.createStatement();

            count = st.executeUpdate(s);

		} catch (SQLException e) {

			m_log.severe("Error [" + e.getMessage() + "] in executing SQL statement [" + s + "]");

			e.printStackTrace();

            throw new LicenseServerException(LicenseServerException.EC_DATABASE_ERROR,

                    "Error in executing a statement without results" + e.getMessage());

		} finally {

            if (st != null) {

                try {

					st.close();

				} catch (SQLException e1) {

                    m_log.severe("Error [" + e1.getMessage() + "] in releasing a handle to a statement");

					e1.printStackTrace();

                    throw new LicenseServerException(LicenseServerException.EC_DATABASE_ERROR,

                            "Error in releasing handle to a statement" + e1.getMessage());

				}    

            }

            freeConnection(con);

        }

        m_log.fine("Statement [" + s + "] affected [" + count + "] row");

        m_log.finer("Leaving Function...");

		return count;

    }

    

    /**

     * Execute a sql statement which returns a result. 

     * Freeing the resources associated with the resultset is the responsibilty of the

     * caller of this method.

     * @param sql statement

     * @return resultset object containing the result of the execution of sql statement.

     */

    public ResultSet executeStatementWithResults(String s)

    throws LicenseServerException {

        m_log.finer("Entering Function...");

        m_log.fine("Going to execute statement [" + s + "] that produces results");

        ResultSet    results = null;

        Connection   con = getConnection();

        Statement    st = null;

        try {

            st = con.createStatement();

            st.executeQuery(s);

            results = st.getResultSet();

        } catch (SQLException e) {

            m_log.severe("Error [" + e.getMessage() + "] in executing SQL statement [" + s + "]");

            e.printStackTrace();

            try {

                if (results != null) {

                    results.close();   

                }

                if (st != null) {

                    st.close();

                }

            } catch (SQLException e1) {

                // TODO Auto-generated catch block

                e1.printStackTrace();

                throw new LicenseServerException(LicenseServerException.EC_DATABASE_ERROR,

                        "Error in releasing resources for a statement with results" + e1.getMessage());

            }    

            freeConnection(con);

            throw new LicenseServerException(LicenseServerException.EC_DATABASE_ERROR,

                    "Error in executing a statement with results" + e.getMessage());

        }

        m_log.fine("Statement [" + s + "] executed");

        m_log.finer("Leaving Function...");

        return results;

    }

    

    /**

     * Free the resources associated with a result set.

     * @param resultset whose resources are to be freed.

     */

    public void releaseResultSetResources(ResultSet res) 

    throws LicenseServerException {

        m_log.finer("Entering Function...");

        if (res == null) {

           return;   

        }

        Statement st = null;

        Connection con = null;

	    try {

            st = res.getStatement();

            res.close();

            if (st != null) {

                con = st.getConnection();   

                st.close();

            }

            freeConnection(con);

	    } catch (SQLException e) {

	       m_log.severe("Error [" + e.getMessage() + "] in releasing result set resources");

	       e.printStackTrace();

           throw new LicenseServerException(LicenseServerException.EC_DATABASE_ERROR,

                   "Error in releasing resources from a result" + e.getMessage());

	    }

        m_log.finer("Leaving Function...");

    }

    

    /**

     * Checks whether a table with a given name exists in the database

     * @param tableName to check

     * @return true if a table with name tableName exists.

     */

    public  boolean hasTable(String tableName) 

    throws LicenseServerException {

        m_log.finer("Entering Function...");

        m_log.fine("Going to find table [" + tableName + "]");

      //  ResultSet   resSet = executeStatementWithResults("show TABLES");

        ResultSet   resSet = executeStatementWithResults(m_listTableSql);

        try {

            while (resSet.next())  {

                String table = resSet.getString(m_tableColumnNumber);

                if (table != null && table.equalsIgnoreCase(tableName)) {

                    m_log.fine("A table with name [" + tableName + "] exists" );

                    return true;            

                }

	        }

	     } catch (SQLException e) {

             m_log.severe("Error in processing table names");

	         e.printStackTrace();

	     } finally {

            releaseResultSetResources(resSet);    

         }

        m_log.fine("A table with name [" + tableName + "] does not exists" );

        m_log.finer("Leaving Function...");

        return false;

    }

    

    /**

     * Returns the count of the number of rows in a result set.

     * Resets the resultset object so that it points before the first row.

     * @param resultset

     * @return number of rows in the resultset.

     */

    public int countNumberInResultSet(ResultSet res) 

    throws LicenseServerException {

        m_log.finer("Entering Function...");

        int count = 0;

        try {

            while (res.next()) {

                count++;

            }

            res.beforeFirst();

        } catch (SQLException e) {

            m_log.severe("Error [" + e.getMessage() + "] in counting items in result.");

            e.printStackTrace();

            throw new LicenseServerException(LicenseServerException.EC_DATABASE_ERROR,

                    "Error in counting number of results in result set" + e.getMessage());

        }

        m_log.fine("There are [" + count + "] items");

        m_log.finer("Leaving Function...");

        return count;

    }

    

    private static  DatabaseHelper  m_databaseHelper   = null;

    private         String          m_databaseURL;

    private         String          m_databaseDriver;

    private         String          m_databaseUser;

    private         String          m_databasePassword;

    private         String          m_listTableSql;

    private         int             m_tableColumnNumber;

    private static  Logger          m_log              = Logger.getLogger(DatabaseHelper.class.getName());

    

    

    // It is recommended that a constructor should not throw an excaeption

    // Error in construction will be tracked by this variable.

    private         boolean         m_initError        = false;

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -