一份关于连接数据库的Util类

自己认认真真总结了一份关于连接数据库的Util类,适用于仍和一种类型的数据库的任何一种Sql语句处理类型,希望大家共同学习,不当的地方望大家不吝赐教:
public class DataTierUtil
    {
        public static bool isInitDatabaseInfo()
        {
            if (Util.isNullStr(DataInfo.DatabaseInfo.DBConnectionString, false))
            {
                return false;
            }
            return true;
        }

        public static void initDatabaseInfo(DataConnType connType, string connString)
        {
            DataInfo.DatabaseInfo.DBConnectionType = connType;
            DataInfo.DatabaseInfo.DBConnectionString = connString;
            DataEngine.InitDataEngine(connType, connString);  
        }

        public static DataSet getDataSet(string strCmd, CommandType cmdType)
        {
            DataSet o = new DataSet() ;
            DbConnection conn = DataConnFactory.instance.newObject(DataInfo.DatabaseInfo.DBConnectionType,
                                                                 DataInfo.DatabaseInfo.DBConnectionString);
            DbDataAdapter adapter = DataAdapterBuilder.buildDataAdapter(DataInfo.DatabaseInfo.DBConnectionType);
            adapter.SelectCommand = buildCommand(null , conn, cmdType, strCmd, null, null);
            switch (DataInfo.DatabaseInfo.DBConnectionType)
            {
                //case DataConnType.OdbcDB:
                //    ((OdbcDataAdapter)adapter).Fill(o);
                //    break;
                //case DataConnType.OleDB:
                //    ((OleDbDataAdapter)adapter).Fill(o);
                //    break;
                case DataConnType.OracleDB:
                    ((OracleDataAdapter)adapter).Fill(o);
                    break;
                case DataConnType.SqlDB:
                    ((SqlDataAdapter)adapter).Fill(o);
                    break;
                case DataConnType.MySqlDB:
                    ((MySqlDataAdapter)adapter).Fill(o);
                    break;
                default:
                    ((OleDbDataAdapter)adapter).Fill(o);
                    break;
            }
            return o;
        }
        public static DataTable PageCache(string PrimaryKey, string DisplayKey, string DataSource, string OrderClause,
                    int PageSize, int PageNo, out int RowCount)
        {
            string[] paras = new string[] { };
            object[] values = new object[] { };
            return PageCache(PrimaryKey, DisplayKey, DataSource, OrderClause, PageSize, PageNo, paras, values, out RowCount);
        }

        public static DataTable PageCache(string PrimaryKey, string DisplayKey, string DataSource, string OrderClause,
            int PageSize, int PageNo, string[] paras, object[] values, out int RowCount)
        {
            DataTable dt = new DataTable();
            string SQL = string.Empty; 
            switch (DataInfo.DatabaseInfo.DBConnectionType)
            {
                case DataConnType.OracleDB:
                    SQL = string.Format("Select {0} from {1}  order by {2}", PrimaryKey, DataSource, OrderClause);
                    break;
                case DataConnType.SqlDB:
                    SQL = string.Format("Select {0} from {1} V order by {2}", PrimaryKey, DataSource, OrderClause);
                    break;
            }
            dt = getDataTable(SQL,CommandType.Text, paras, values);
            RowCount = dt.Rows.Count;    //需要返回总记录数
            //if(RowCount == 0) return null ;
            int lStartRow = PageSize * (PageNo - 1) + 1;
            int lEndRow = lStartRow + PageSize - 1;
            //if (lStartRow > RowCount) return null ;
            if (lEndRow > RowCount) lEndRow = RowCount;
            string WhereClause = string.Empty;
            bool bIn =  dt.Columns[0].DataType == typeof(String) 
                || dt.Columns[0].DataType == typeof(string) 
                ||  dt.Columns[0].DataType==typeof(DateTime);   
            for (int i = lStartRow - 1; i < lEndRow; i++)
            {
                if (bIn)
                {
                    WhereClause = WhereClause + "'" + dt.Rows[i][0] + "',";
                }
                else
                {
                    WhereClause = WhereClause + dt.Rows[i][0] + ",";
                }
            }
            if (WhereClause.Length > 0) 
                WhereClause = WhereClause.Substring(0, WhereClause.Length - 1);
            else
                WhereClause = bIn? "''":"-1";
            int NumIndex = PrimaryKey.IndexOf(".");
            if (NumIndex > 0) PrimaryKey = PrimaryKey.Substring(NumIndex + 1);
            switch (DataInfo.DatabaseInfo.DBConnectionType)
            {
                case DataConnType.OracleDB:
                    SQL = string.Format("Select * from (Select {0} from {1} order by {4}) where {2} in ({3})",
                DisplayKey, DataSource, PrimaryKey, WhereClause, OrderClause);
                    break;
                case DataConnType.SqlDB:
                    SQL = string.Format("Select * from (Select {0} from {1} V1 )V where {2} in ({3})  order by {4}",
                DisplayKey, DataSource, PrimaryKey, WhereClause, OrderClause);
                    break;
            }
            dt = getDataTable(SQL,CommandType.Text, paras, values);
            return dt; //返回当前页的查询记录
        }

        public static DataTable getDataTable(string strCmd, CommandType cmdType)
        {
            return fillDataTable(null, null, null, strCmd, cmdType, null, null);
        }

        public static DataTable getDataTable(string strCmd, CommandType cmdType, string[] paramNames,
                                             object[] paramValues)
        {
            return fillDataTable(null, null, null, strCmd, cmdType, paramNames, paramValues);
        }

        public static DataTable getDataTable(DbTransaction trans, string strCmd, CommandType cmdType)
        {
            return fillDataTable(null, trans, null, strCmd, cmdType, null, null);
        }

        public static DataTable getDataTable(DbTransaction trans, string strCmd, CommandType cmdType,
                                             string[] paramNames, object[] paramValues)
        {
            return fillDataTable(null, trans, null, strCmd, cmdType, paramNames, paramValues);
        }

        public static DataTable getDataTable(DbConnection conn, string strCmd, CommandType cmdType)
        {
            return fillDataTable(null, null, conn, strCmd, cmdType, null, null);
        }

        public static DataTable getDataTable(DbConnection conn, string strCmd, CommandType cmdType, string[] paramNames,
                                             object[] paramValues)
        {
            return fillDataTable(null, null, conn, strCmd, cmdType, paramNames, paramValues);
        }

        public static DataTable fillDataTable(DataTable table, string strCmd, CommandType cmdType)
        {
            return fillDataTable(table, null, null, strCmd, cmdType, null, null);
        }

        public static DataTable fillDataTable(DataTable table, string strCmd, CommandType cmdType, string[] paramNames,
                                              object[] paramValues)
        {
            return fillDataTable(table, null, null, strCmd, cmdType, paramNames, paramValues);
        }

        public static DataTable fillDataTable(DbTransaction trans, DataTable table, string strCmd, CommandType cmdType)
        {
            return fillDataTable(table, trans, null, strCmd, cmdType, null, null);
        }

        public static DataTable fillDataTable(DbTransaction trans, DataTable table, string strCmd, CommandType cmdType,
                                              string[] paramNames, object[] paramValues)
        {
            return fillDataTable(table, trans, null, strCmd, cmdType, paramNames, paramValues);
        }

        public static DataTable fillDataTable(DbConnection conn, DataTable table, string strCmd, CommandType cmdType)
        {
            return fillDataTable(table, null, conn, strCmd, cmdType, null, null);
        }

        public static DataTable fillDataTable(DbConnection conn, DataTable table, string strCmd, CommandType cmdType,
                                              string[] paramNames, object[] paramValues)
        {
            return fillDataTable(table, null, conn, strCmd, cmdType, paramNames, paramValues);
        }

        private static DataTable fillDataTable(DataTable table, DbTransaction trans, DbConnection conn, string strCmd,
                                               CommandType cmdType, string[] paramNames, object[] paramValues)
        {
            bool isNewConn = false;
            if (table == null)
            {
                table = new DataTable();
            }
            try
            {
                if (trans == null)
                {
                    if (conn == null)
                    {
                        isNewConn = true;
                        conn =
                            DataConnFactory.instance.newObject(DataInfo.DatabaseInfo.DBConnectionType,
                                                                 DataInfo.DatabaseInfo.DBConnectionString);
                    }
                }
                else
                {
                    conn = trans.Connection;
                }
                DbDataAdapter adapter = DataAdapterBuilder.buildDataAdapter(DataInfo.DatabaseInfo.DBConnectionType);
                adapter.SelectCommand = buildCommand(trans, conn, cmdType, strCmd, paramNames, paramValues);
                switch (DataInfo.DatabaseInfo.DBConnectionType)
                {
                    //case DataConnType.OdbcDB:
                    //    ((OdbcDataAdapter)adapter).Fill(table);
                    //    break;
                    //case DataConnType.OleDB:
                    //    ((OleDbDataAdapter)adapter).Fill(table);
                    //    break;
                    case DataConnType.OracleDB:
                        ((OracleDataAdapter)adapter).Fill(table);
                        break;
                    case DataConnType.SqlDB:
                        ((SqlDataAdapter)adapter).Fill(table);
                        break;
                    case DataConnType.MySqlDB:
                        ((MySqlDataAdapter)adapter).Fill(table);
                        break;
                    default:
                        ((OleDbDataAdapter)adapter).Fill(table);
                        break;
                }
            }
            catch (Exception ex)
            {
                throw new DataTierException(ex.Message);
            }
            finally
            {
                if (trans == null)
                {
                    if (isNewConn)
                    {
                        DataConnFactory.instance.closeObject(conn);
                    }
                }
            }
            return table;
        }

        private static DbCommand buildCommand(DbTransaction trans, DbConnection conn, CommandType cmdType,
                                               string strCmd, string[] strParams, object[] strValues)
        {
            DbCommand command = conn.CreateCommand();
            switch (DataInfo.DatabaseInfo.DBConnectionType)
            {
                case DataConnType.SqlDB:
                    command.CommandText = strCmd.Replace(":", "@");
                    break;
                case DataConnType.OracleDB:
                    strCmd = strCmd.Replace("'@", "{$}");
                    strCmd = strCmd.Replace("@", ":");
                    command.CommandText = strCmd.Replace("{$}", "'@");
                    command.CommandText = command.CommandText.Replace("#", "@");
                    break;
                //case DataConnType.OleDB:
                //    strCmd = strCmd.Replace("'@", "{$}");
                //    if (strParams != null)
                //    {
                //        for (int i = 0; i < strParams.Length; i++)
                //        {
                //            strCmd = strCmd.Replace(strParams[i], "?");
                //        }
                //    }
                //    break;
                case DataConnType.MySqlDB:
                    command.CommandText = strCmd.Replace("@", "?");
                    break;
            }
            command.CommandType = cmdType;
            if (trans != null)
            {
                command.Transaction = trans;
            }
            else
            {
                command.Transaction = null;
            }
            if ((strParams != null) && (strValues != null))
            {
                long length = strParams.Length;
                if (length != strValues.Length)
                {
                    throw new DataTierException(string.Concat(new object[] { " ", length, " ", strValues.Length, "" }));
                }
                for (int j = 0; j < length; j++)
                {
                    command.Parameters.Add(createParameter(strParams[j], strValues[j]));
                }
            }
            return command;
        }

        private static DbParameter createParameter(string strParam, object val)
        {
            if (val == null)
            {
                val = DBNull.Value;
            }
            switch (DataInfo.DatabaseInfo.DBConnectionType)
            {
                case DataConnType.SqlDB:
                    if (strParam.StartsWith("@"))
                    {
                        return new SqlParameter(strParam, val);
                    }
                    return new SqlParameter("@" + strParam, val);

                case DataConnType.OracleDB:
                    return new OracleParameter(strParam.Replace("@", ""), val);
                case DataConnType.MySqlDB:
                    return new MySqlParameter(strParam.Replace("@", "?"), val);
            }
            return new OleDbParameter(strParam.Replace("@", ""), val);
        }

        public static int executeNoQuery(DbTransaction trans, string strCmd, CommandType cmdType)
        {
            return executeNoQuery(trans, null, strCmd, cmdType, null, null);
        }

        public static int executeNoQuery(DbTransaction trans, string strCmd, CommandType cmdType, string[] paramNames,
                                         object[] paramValues)
        {
            return executeNoQuery(trans, null, strCmd, cmdType, paramNames, paramValues);
        }

        public static int executeNoQuery(DbConnection conn, string strCmd, CommandType cmdType)
        {
            return executeNoQuery(null, conn, strCmd, cmdType, null, null);
        }

        public static int executeNoQuery(DbConnection conn, string strCmd, CommandType cmdType, string[] paramNames,
                                         object[] paramValues)
        {
            return executeNoQuery(null, conn, strCmd, cmdType, paramNames, paramValues);
        }

        public static int executeNoQuery(string strCmd, CommandType cmdType)
        {
            return executeNoQuery(null, null, strCmd, cmdType, null, null);
        }

        public static int executeNoQuery(string strCmd, CommandType cmdType, string[] paramNames, object[] paramValues)
        {
            return executeNoQuery(null, null, strCmd, cmdType, paramNames, paramValues);
        }

        private static int executeNoQuery(DbTransaction trans, DbConnection conn, string strCmd, CommandType cmdType,
                                          string[] paramNames, object[] paramValues)
        {
            bool isNewConn = false;
            int num;
            try
            {
                if (trans == null)
                {
                    if (conn == null)
                    {
                        isNewConn = true;
                        conn =
                            DataConnFactory.instance.newObject(DataInfo.DatabaseInfo.DBConnectionType,
                                                                 DataInfo.DatabaseInfo.DBConnectionString);
                    }
                }
                else
                {
                    conn = trans.Connection;
                }
                num = buildCommand(trans, conn, cmdType, strCmd, paramNames, paramValues).ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new DataTierException(ex.Message);
            }
            finally
            {
                if (trans == null)
                {
                    if (isNewConn)
                    {
                        DataConnFactory.instance.closeObject(conn);
                    }
                }
            }
            return num;
        }

        public static DbDataReader getDataReader(DbTransaction trans, string strCmd, CommandType cmdType)
        {
            return getDataReader(trans, null, strCmd, cmdType, null, null);
        }

        public static DbDataReader getDataReader(DbTransaction trans, string strCmd, CommandType cmdType,
                                                string[] paramNames, object[] paramValues)
        {
            return getDataReader(trans, null, strCmd, cmdType, paramNames, paramValues);
        }

        public static DbDataReader getDataReader(DbConnection conn, string strCmd, CommandType cmdType)
        {
            return getDataReader(null, conn, strCmd, cmdType, null, null);
        }

        public static DbDataReader getDataReader(DbConnection conn, string strCmd, CommandType cmdType,
                                                string[] paramNames, object[] paramValues)
        {
            return getDataReader(null, conn, strCmd, cmdType, paramNames, paramValues);
        }

        private static DbDataReader getDataReader(DbTransaction trans, DbConnection conn, string strCmd,
                                                 CommandType cmdType, string[] paramNames, object[] paramValues)
        {
            try
            {
                if (trans == null)
                {
                    if (conn == null)
                    {
                        throw new DataTierException("没有数据连接");
                    }
                }
                else
                {
                    conn = trans.Connection;
                }
                return buildCommand(trans, conn, cmdType, strCmd, paramNames, paramValues).ExecuteReader();
            }
            catch (Exception ex)
            {
                throw new DataTierException(ex.Message);
            }
        }

        public static DbDataReader getDataReader(DbTransaction trans, string strCmd, CommandType cmdType,
                                                CommandBehavior behavior)
        {
            return getDataReader(trans, null, strCmd, cmdType, behavior, null, null);
        }

        public static DbDataReader getDataReader(DbTransaction trans, string strCmd, CommandType cmdType,
                                                CommandBehavior behavior, string[] paramNames, object[] paramValues)
        {
            return getDataReader(trans, null, strCmd, cmdType, behavior, paramNames, paramValues);
        }

        public static DbDataReader getDataReader(DbConnection conn, string strCmd, CommandType cmdType,
                                                CommandBehavior behavior)
        {
            return getDataReader(null, conn, strCmd, cmdType, behavior, null, null);
        }

        public static DbDataReader getDataReader(DbConnection conn, string strCmd, CommandType cmdType,
                                                CommandBehavior behavior, string[] paramNames, object[] paramValues)
        {
            return getDataReader(null, conn, strCmd, cmdType, behavior, paramNames, paramValues);
        }

        private static DbDataReader getDataReader(DbTransaction trans, DbConnection conn, string strCmd,
                                                 CommandType cmdType, CommandBehavior behavior,
                                                 string[] paramNames, object[] paramValues)
        {
            try
            {
                if (trans == null)
                {
                    if (conn == null)
                    {
                        throw new DataTierException("没有数据连接");
                    }
                }
                else
                {
                    conn = trans.Connection;
                }
                //return buildCommand(trans, conn, cmdType, strCmd, paramNames, paramValues).ExecuteReader(behavior);
                return buildCommand(trans, conn, cmdType, strCmd, paramNames, paramValues).ExecuteReader();
            }
            catch (Exception ex)
            {
                throw new DataTierException(ex.Message);
            }
        }

        public static DbDataReader getDataReader(string strCmd, CommandType cmdType)
        {
            DbConnection conn =
                DataConnFactory.instance.newObject(DataInfo.DatabaseInfo.DBConnectionType,
                                                     DataInfo.DatabaseInfo.DBConnectionString);
            return getDataReader(null, conn, strCmd, cmdType, CommandBehavior.CloseConnection, null, null);
        }

        public static DbDataReader getDataReader(string strCmd, CommandType cmdType, string[] paramNames,
                                                object[] paramValues)
        {
            DbConnection conn =
                DataConnFactory.instance.newObject(DataInfo.DatabaseInfo.DBConnectionType,
                                                     DataInfo.DatabaseInfo.DBConnectionString);
            return getDataReader(null, conn, strCmd, cmdType, CommandBehavior.CloseConnection, paramNames, paramValues);
        }

        public static object getScalar(DbTransaction trans, string strCmd, CommandType cmdType)
        {
            return getScalar(trans, null, strCmd, cmdType, null, null);
        }

        public static object getScalar(DbTransaction trans, string strCmd, CommandType cmdType, string[] paramNames,
                                       object[] paramValues)
        {
            return getScalar(trans, null, strCmd, cmdType, paramNames, paramValues);
        }

        public static object getScalar(DbConnection conn, string strCmd, CommandType cmdType)
        {
            return getScalar(null, conn, strCmd, cmdType, null, null);
        }

        public static object getScalar(DbConnection conn, string strCmd, CommandType cmdType, string[] paramNames,
                                       object[] paramValues)
        {
            return getScalar(null, conn, strCmd, cmdType, paramNames, paramValues);
        }

        public static object getScalar(string strCmd, CommandType cmdType)
        {
            return getScalar(null, null, strCmd, cmdType, null, null);
        }

        public static object getScalar(string strCmd, CommandType cmdType, string[] paramNames, object[] paramValues)
        {
            return getScalar(null, null, strCmd, cmdType, paramNames, paramValues);
        }

        private static object getScalar(DbTransaction trans, DbConnection conn, string strCmd, CommandType cmdType,
                                        string[] paramNames, object[] paramValues)
        {
            bool isNewConn = false;
            try
            {
                if (trans == null)
                {
                    if (conn == null)
                    {
                        isNewConn = true;
                        conn =
                            DataConnFactory.instance.newObject(DataInfo.DatabaseInfo.DBConnectionType,
                                                                 DataInfo.DatabaseInfo.DBConnectionString);
                    }
                }
                else
                {
                    conn = trans.Connection;
                }
                return buildCommand(trans, conn, cmdType, strCmd, paramNames, paramValues).ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw new DataTierException(ex.Message);
            }
            finally
            {
                if (trans == null)
                {
                    if (isNewConn)
                    {
                        DataConnFactory.instance.closeObject(conn);
                    }
                }
            }
        }

        /// <summary>
        /// 开始事务
        /// </summary>
        public static void beginTransaction(out DbTransaction trans)
        {
            try
            {
                DbConnection conn = DataConnFactory.instance.newObject(DataInfo.DatabaseInfo.DBConnectionType,
                                                                          DataInfo.DatabaseInfo.DBConnectionString);
                trans = conn.BeginTransaction();
            }
            catch (Exception ex)
            {
                throw new DataTierException(ex.Message);
            }
        }

       /// <summary>
       /// 回滚事务
       /// </summary>
        public static void rollbackTransaction(ref DbTransaction trans)
        {
            if (trans != null)
            {
                if (trans.Connection != null)
                {
                    trans.Rollback();
                    if (trans.Connection != null)
                    {
                        if (trans.Connection.State == ConnectionState.Open)
                        {
                            trans.Connection.Close();
                        }
                        trans.Connection.Dispose();
                    }
                }
                trans = null;
            }
        }

       /// <summary>
       /// 结束事务
       /// </summary>
        public static void endTransaction(ref DbTransaction trans)
        {
            if (trans != null)
            {
                if (trans.Connection != null)
                {
                    trans.Commit();
                    if (trans.Connection != null)
                    {
                        if (trans.Connection.State == ConnectionState.Open)
                        {
                            trans.Connection.Close();
                        }
                        trans.Connection.Dispose();
                    }
                }
                trans = null;
            }
        }
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.sql.*; import java.util.*; /** * * Title: 数据库工具 * * * Description: 将大部分的数据库操作放入这个中, 包括数据库连接的建立, 自动释放等. * * * @author beansoft 日期: 2004年04月 * @version 2.0 */ public class DatabaseUtil { /** 数据库连接 */ private java.sql.Connection connection; /** * All database resources created by this class, should be free after all * operations, holds: ResultSet, Statement, PreparedStatement, etc. */ private ArrayList resourcesList = new ArrayList(5); public DatabaseUtil() { } /** 关闭数据库连接并释放所有数据库资源 */ public void close() { closeAllResources(); close(getConnection()); } /** * Close given connection. * * @param connection * Connection */ public static void close(Connection connection) { try { connection.close(); } catch (Exception ex) { System.err.println("Exception when close a connection: " + ex.getMessage()); } } /** * Close all resources created by this class. */ public void closeAllResources() { for (int i = 0; i < this.getResourcesList().size(); i++) { closeJDBCResource(getResourcesList().get(i)); } } /** * Close a jdbc resource, such as ResultSet, Statement, Connection.... All * these objects must have a method signature is void close(). * * @param resource - * jdbc resouce to close */ public void closeJDBCResource(Object resource) { try { Class clazz = resource.getClass(); java.lang.reflect.Method method = clazz.getMethod("close", null); method.invoke(resource, null); } catch (Exception e) { // e.printStackTrace(); } } /** * 执行 SELECT 等 SQL 语句并返回结果集. * * @param sql * 需要发送到数据库 SQL 语句 * @return a ResultSet object that contains the data produced * by the given query; never null */ public ResultSet executeQuery(String sql) { try { Statement statement = getStatement(); ResultSet rs = statement.executeQuery(sql); this.getResourcesList().add(rs); this.getResourcesList().add(statement);// BUG fix at 2006-04-29 by BeanSoft, added this to res list // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); return rs; } catch (Exception ex) { System.out.println("Error in executeQuery(\"" + sql + "\"):" + ex); // ex.printStackTrace(); return null; } } /** * Executes the given SQL statement, which may be an INSERT, * UPDATE, or DELETE statement or an SQL * statement that returns nothing, such as an SQL DDL statement. 执行给定的 SQL * 语句, 这些语句可能是 INSERT, UPDATE 或者 DELETE 语句, 或者是一个不返回任何东西的 SQL 语句, 例如一个 SQL * DDL 语句. * * @param sql * an SQL INSERT,UPDATE or * DELETE statement or an SQL statement that * returns nothing * @return either the row count for INSERT, * UPDATE or DELETE statements, or * 0 for SQL statements that return nothing */ public int executeUpdate(String sql) { try { Statement statement = getStatement(); return statement.executeUpdate(sql); // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); } catch (Exception ex) { System.out.println("Error in executeUpdate(): " + sql + " " + ex); //System.out.println("executeUpdate:" + sql); ex.printStackTrace(); } return -1; } /** * 返回记录总数, 使用方法: getAllCount("SELECT count(ID) from tableName") 2004-06-09 * 可滚动的 Statement 不能执行 SELECT MAX(ID) 之的查询语句(SQLServer 2000) * * @param sql * 需要执行的 SQL * @return 记录总数 */ public int getAllCount(String sql) { try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); ResultSet rs = statement.executeQuery(sql); rs.next(); int cnt = rs.getInt(1); rs.close(); try { statement.close(); this.getResourcesList().remove(statement); } catch (Exception ex) { ex.printStackTrace(); } return cnt; } catch (Exception ex) { System.out.println("Exception in DatabaseUtil.getAllCount(" + sql + "):" + ex); ex.printStackTrace(); return 0; } } /** * 返回当前数据库连接. */ public java.sql.Connection getConnection() { return connection; } /** * 连接新的数据库对象到这个工具, 首先尝试关闭老连接. */ public void setConnection(java.sql.Connection connection) { if (this.connection != null) { try { getConnection().close(); } catch (Exception ex) { } } this.connection = connection; } /** * Create a common statement from the database connection and return it. * * @return Statement */ public Statement getStatement() { // 首先尝试获取可滚动的 Statement, 然后才是普通 Statement Statement updatableStmt = getUpdatableStatement(); if (updatableStmt != null) return updatableStmt; try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getStatement(): " + ex); } return null; } /** * Create a updatable and scrollable statement from the database connection * and return it. * * @return Statement */ public Statement getUpdatableStatement() { try { Statement statement = getConnection() .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getUpdatableStatement(): " + ex); } return null; } /** * Create a prepared statement and return it. * * @param sql * String SQL to prepare * @throws SQLException * any database exception * @return PreparedStatement the prepared statement */ public PreparedStatement getPreparedStatement(String sql) throws SQLException { try { PreparedStatement preparedStatement = getConnection() .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(preparedStatement); return preparedStatement; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Return the resources list of this class. * * @return ArrayList the resources list */ public ArrayList getResourcesList() { return resourcesList; } /** * Fetch a string from the result set, and avoid return a null string. * * @param rs * the ResultSet * @param columnName * the column name * @return the fetched string */ public static String getString(ResultSet rs, String columnName) { try { String result = rs.getString(columnName); if (result == null) { result = ""; } return result; } catch (Exception ex) { } return ""; } /** * Get all the column labels * * @param resultSet * ResultSet * @return String[] */ public static String[] getColumns(ResultSet resultSet) { if (resultSet == null) { return null; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); if (numberOfColumns <= 0) { return null; } String[] columns = new String[numberOfColumns]; //System.err.println("numberOfColumns=" + numberOfColumns); // Get the column names for (int column = 0; column < numberOfColumns; column++) { // System.out.print(metaData.getColumnLabel(column + 1) + "\t"); columns[column] = metaData.getColumnName(column + 1); } return columns; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Get the row count of the result set. * * @param resultset * ResultSet * @throws SQLException * if a database access error occurs or the result set type is * TYPE_FORWARD_ONLY * @return int the row count * @since 1.2 */ public static int getRowCount(ResultSet resultset) throws SQLException { int row = 0; try { int currentRow = resultset.getRow(); // Remember old row position resultset.last(); row = resultset.getRow(); if (currentRow > 0) { resultset.absolute(row); } } catch (Exception ex) { ex.printStackTrace(); } return row; } /** * Get the column count of the result set. * * @param resultSet * ResultSet * @return int the column count */ public static int getColumnCount(ResultSet resultSet) { if (resultSet == null) { return 0; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); return numberOfColumns; } catch (Exception ex) { ex.printStackTrace(); } return 0; } /** * Read one row's data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * @param resultSet * ResultSet * @return Hashtable */ public static final Hashtable readResultToHashtable(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { resultHash.put(columns[i], getString(resultSet, columns[i])); } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** * Read data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * Note: assume the default database string encoding is ISO8859-1. * * @param resultSet * ResultSet * @return Hashtable */ @SuppressWarnings("unchecked") public static final Hashtable readResultToHashtableISO(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { String isoString = getString(resultSet, columns[i]); try { resultHash.put(columns[i], new String(isoString .getBytes("ISO8859-1"), "GBK")); } catch (Exception ex) { resultHash.put(columns[i], isoString); } } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** Test this class. */ public static void main(String[] args) throws Exception { DatabaseUtil util = new DatabaseUtil(); // TODO: 从连接池工厂获取连接 // util.setConnection(ConnectionFactory.getConnection()); ResultSet rs = util.executeQuery("SELECT * FROM e_hyx_trans_info"); while (rs.next()) { Hashtable hash = readResultToHashtableISO(rs); Enumeration keys = hash.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); System.out.println(key + "=" + hash.get(key)); } } rs.close(); util.close(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值