您的位置:首页 > 博客中心 > 数据库 >

数据库操作通用类

时间:2022-03-10 17:21

DataBase.java
 
说明:
1. 此类包含对数据库的查询,删除,更新操作.
    2. 可以实现对大文本对象的增删改.
    3. 利用自建的数据库连接池类, 得到数据库连接.
    4. 可以利用Tomcat 自带的连接池, 得到数据库连接
 
变量:
    1. 数据库连接
    变量名     : conn
    应用范围   : protect
    变量类型   : Connection 数据库连接
    初始值     : null
    是否Static :  否
    2. 声明语句
    变量名     : stm
    应用范围   : protect
    变量类型   : Statement
    初始值     : null
    是否Static : 否
    3. 预声明语句
    变量名     : pstm
    应用范围   : protect
    变量类型   : PreparedStatement
    初始值     : null
    是否Static : 否
    4. 结果集
    变量名     : rs
    应用范围   : protect
    变量类型   : ResultSet
    初始值     : null
    是否Static : 否
    5. 标识是否取得连接
    变量名     : connected
    应用范围   : protect
    变量类型   : boolean
    初始值     : false
    是否Static : 否
方法简介
序号
方法名
参数
返回值
功能
1
DataBase Void 构造函数
2
showConnNum Void 在控件台显示当前连接池情况,连接数,总连接数等信息
3
getConnPool Void
* 取得Tomcat连接池, 在server.xml 中配置的连接池
* 从连接池中取得连接
4
getMyConnPool Void
* 创建连接池, 并取得连接
* 从由连接池类DBConnectionManager 创建的连接池
5
releaseMyConnPool Boolean 释放我的连接池, 即由DBConnectionManager 创建的连接池
6
createConn
String drv
String url
String usr
String pwd
Void
* 生成Oracle SQLServer 等的连接
* 不使用连接池
7
createConn
String drv
String url
Void 生成Access连接
8
realaseConn Void 释放的是当前类中, 通过各种方法取得的连接
9
QuerySql String sql ResultSet 执行查询sql 语句, 并返回执行结果
10
ExceuteSql String sql Int 执行删除sql 语句, 自动提交, 成功返回0,失败返回错误代码
11
getOnePage
String sql
int page
int records
Vector
执行查询sql 语句
将页号为page , 每页显示records条记录的结果集,以键/值对应的形式存入Hashtable 并存入Vector
12
getOnePage1
String sql
int page
int records
Boolean b
Vector
执行查询sql 语句
将页号为page , 每页显示records条记录的结果集,以键/值对应的形式存入Hashtable 并存入Vector
13
getOnePage
String sql
int page
int records boolean useDic
Vector
执行查询sql 语句
将页号为page , 每页显示records条记录的结果集,以键/值对应的形式存入Hashtable 并存入Vector
如果useDic 为true , 从配置表中取每面显示记录数
14
getData String sql Vector
执行查询sql 语句
将结果以 列/值对应的存入Hashtabl中, 存入Vector
15
QueryClob
String table String wherestr
String clobfield
String
查询 Clob型字段的值
将Clob结果转换为String , 并返回String
16
UpdateClob
String table String wherestr
String clobfield
String clobvalue
Int
将clobvalue 转换为clob
用转换后的clob 更新clobfield字段
成功返回0 , 失败返回错误代码
17
QueryBlob String table String wherestr String blobfield String
查询 Blob 型字段的值
将Blob 结果转换为String , 并返回String
18
UpdateBlob
String table String wherestr
String blobfield String blobvalue
Int
将blobvalue 转换为blob
用转换后的blob 更新blobfield字段
成功返回0 , 失败返回错误代码
19
QueryBLOB_JNDI String table String wherestr String blobfield String 查询blob 型字段, 返回String
20
UpdateBLOB_JNDI String table String wherestr String blobfield String blobvalue Int 更新blob 型辽段
21
clobInsert
String sql String table String wherestr
String clobfield String infile
Int
往数据库中插入一个新的CLOB对象
sql 是一条插入语句
22
clobModify
String table String wherestr String clobfield
String infile
int 修改CLOB对象(是在原CLOB对象基础上进行覆盖式的修改)
23
clobReplace
String table String wherestr String clobfield
String infile
Int 替换CLOB对象(将原CLOB对象清除,换成一个全新的CLOB对象)
24
blobInsert
String sql String table String wherestr
String blobfield
String infile
int 向数据库中插入一个新的BLOB对象
25
blobModify
String table String wherestr String blobfield
            String infile
int 修改BLOB对象(是在原BLOB对象基础上进行覆盖式的修改)
26
blobReplace
String table String wherestr String blobfield
String infile
int 替换BLOB对象(将原BLOB对象清除,换成一个全新的CLOB对象)
27
getDataBaseInfo   Hashtable 数据库信息(类型,版本,驱动等) 使用DatabaseMetaData类
28
getTableList   Vector 使用DatabaseMetaData类的getTables
29
getTableStruct String table Vector 数据表的结构(字段名,类型,是否为空,精度等) DatabaseMetaData类
30
getResultSetData ResultSet rs Vector 列/值 存入Hashtable, 将Hashtable 存入Vector中
31
prepareStatement String sql Void 用sql 创建表达, 为类变量pstm 赋值
32
executeQuery void 执行查询, 执行变量pstm中设置的表达, 返回结果集赋给类变量rs
33
next boolean 调用rs.next(), 转向下一条记录
34
getObject String field String sqlType String 取得数据并根据数据类型转化为字符串
35
setObject
int index
String value
String sqlType
Void
根据数据类型保存到数据库
根据将参数sqlType 将value 转换为相应的类型
调用 psmt.setObject(index, 转换后的value)
36
executeUpdate Void 调用 psmt.executeUpdate() , 执行数据更新
37
closePstm Void 调用 psmt.close(), 关闭表达对象
38
closeRs Void 调用 rs.close(), 关闭结果集
39
setBinaryStream int index InputStream is int t Void 调用 pstm.setBinaryStream(index, is, t);
40
setAsciiStream int index InputStream is int t Void 调用 pstm.setBinaryStream(index, is, t);
41
getAutoCommit   boolean 调用conn.getAutoCommit(); 判断是否自动提交
42
closeAutoCommit   Void 调用 conn.setAutoCommit(false);
43
commit   Void 调用 conn.commit()
44
Rollback   Void 调用 conn.rollback()
45
openAutoCommit   Void 调用 conn.setAutoCommit(true)
46
createStatement   Void 调用 stm = conn.createStatement();
47
clearBatch   void 调用 stm.clearBatch();
48
addBatch   Void 调用 stm.addBatch(sql);
49
executeBatch   Int[] 调用 stm.executeBatch();
50
closeStm   Void 调用 stm.close()
 
方法详解
 
package oa.main;
 
import java.util.*;
import java.sql.*;
import java.io.*;
import javax.naming.*;
/**
 * 此文件为数据库的基本操作处理类
 * 
 * @author zhoumeng
 * @version 1.0
 */
public class DataBase extends Object
{
    Connection        conn      = null; // 连接
    Statement          stm       = null; //
    PreparedStatement pstm      = null; //
 
    ResultSet         rs                = null; // 结果集
    boolean           connected = false;// 是否连接
    /** 构造函数 */
    public DataBase()
    {
    }

    /**
     *  在控制台显示连接池情况
     * 
     * */

    public void showConnNUM()
    {
        /**---------------------------------------------------------------------------------------------------------------**/
        // 字符操作类
        DealString ds = new DealString();
        **---------------------------------------------------------------------------------------------------------------**/
        // 连接池信息
        int curnum        = DBConnectionManager
             .getCurConns(Configuration.ConnectionPoolName);  
// 现有连接数 
        int sumnum      = DBConnectionManager
             .getSumConns(Configuration.ConnectionPoolName); 
// 连接总数
        int maxnum      = DBConnectionManager
             .getMaxConns(Configuration.ConnectionPoolName);  
// 池中连接
        int isNullPool  = DBConnectionManager
             .getNullPool(Configuration.ConnectionPoolName);     
 // 池中空连接数
        int isOracleErr = DBConnectionManager
             .getOracleErr(Configuration.ConnectionPoolName);   
// 错误连接数
        **---------------------------------------------------------------------------------------------------------------**/       
        int jvmcount    = ParentBean.count;
        float jvm1        = (float) Runtime.getRuntime().totalMemory() / 1024 / 1024;
        float jvm2        = (float) Runtime.getRuntime().maxMemory() / 1024 / 1024;
        **---------------------------------------------------------------------------------------------------------------**/
        System.out.print("/r"  + ds.getDateTime().substring(11, 19)             + 
                "程序中调用连接累计数> "   + ds.toLengthStrRight(sumnum  + "", 10)      + 
                "当前非空闲的连接总数> "   + ds.toLengthStrRight(curnum    + "", 10)      + 
                "连接数(空闲+非空闲)  > "    + ds.toLengthStrRight(maxnum   + "", 10)      + 
                "超出连接数限制的请求> "   + ds.toLengthStrRight(isNullPool+ "", 10)      + 
                "DB未响应> "   + ds.toLengthStrRight(isOracleErr + "", 10) + 
                "JVM垃圾回收> "+ jvmcount + "  ");
    }
    /** 
     * 
     * 取得Tomcat连接池, 在server.xml 中配置的连接池
     * 从连接池中取得连接
     * */
    public void getConnPool()
    {
        try {
            /**---------------------------------------------------------------------------------------------------------------**/
            if (connected) // 已经连接
            {
                throw new SQLException("数据库已连接,无须重连!");
            }
            /**---------------------------------------------------------------------------------------------------------------**/
            // 上下文环境
            Context initCtx = new InitialContext();
            Context ctx       = (Context) initCtx.lookup("java:comp/env");
            /**---------------------------------------------------------------------------------------------------------------**/
            /** 获取连接池对象 */
            Object obj = (Object) ctx.lookup("jdbc/OracleDB");
            /**---------------------------------------------------------------------------------------------------------------**/
            /** 类型转换 */
            javax.sql.DataSource ds = (javax.sql.DataSource) obj;
            /**---------------------------------------------------------------------------------------------------------------**/
            // 从连接池中得到连接
            conn = ds.getConnection();
            /**---------------------------------------------------------------------------------------------------------------**/
            // 标识已得到连接池, 并得到连接
            connected = true;
            /**---------------------------------------------------------------------------------------------------------------**/
            // 控件台输出连接情况
            showConnNUM();
        } catch (NamingException e) {
            System.out.println("从数据池取得数据库连接时出错;/r/n错误为:" + e);
        } catch (SQLException e) {
            System.out.println("从数据池取得数据库连接时出错;/r/n错误为:" + e);
        }
    }

    /** 
     * 创建连接池, 并取得连接
     * 从由连接池类DBConnectionManager 创建的连接池 
     * 
     * */
    public boolean getMyConnPool()
    {
        /**---------------------------------------------------------------------------------------------------------------**/
        // 创建连接池实例, 并取得连接
        conn = Configuration.connMgr
                .getConnection(Configuration.ConnectionPoolName);
        /**---------------------------------------------------------------------------------------------------------------**/
        // 显示连接池情况
        showConnNUM();
        /**---------------------------------------------------------------------------------------------------------------**/
        // 判断方法是否执行成功, 连接为空返回false , 连接不为空返回true
        if (conn == null)
        {
            return false;
        } else {
            return true;
        }
    }

    /** 
     * 释放我的连接池中的连接
     * 通过连接池管理类DBConnectionManager 生成的连接
     * */
    public boolean releaseMyConnPool()
    {
        /**---------------------------------------------------------------------------------------------------------------**/
        // 判断是否已连接
        boolean b;
        if (conn != null)
        {
            b = true;
        } else {
            b = false;
        }
        /**---------------------------------------------------------------------------------------------------------------**/
        // 调用DBConnectionManager 中的freeConnection 方法, 释放指定连接
        // 池中的指定连接
        Configuration.connMgr
         .freeConnection(Configuration.ConnectionPoolName, conn);
        /**---------------------------------------------------------------------------------------------------------------**/       
        // 连接置为空
        conn = null;
        /**---------------------------------------------------------------------------------------------------------------**/
        // 控件台显示连接池情况
        showConnNUM();
        
        return b;
    }

    /** 
     * 生成Oracle SQLServer 等的连接 
     * 不使用连接池
     * */
    public void createConn(String drv, String url, String usr, String pwd)
    {
         try{
             /**---------------------------------------------------------------------------------------------------------------**/
             if (connected)
             {
                 throw new SQLException("数据库已连接,无须重连!");
             }
             /**---------------------------------------------------------------------------------------------------------------**/
             // JDBC 或 JDBC-ODBC 连接, 依据url而定
             Class.forName(drv).newInstance();
             conn = DriverManager.getConnection(url, usr, pwd);
             /**---------------------------------------------------------------------------------------------------------------**/
             connected = true;
             /**---------------------------------------------------------------------------------------------------------------**/
             // 控件台显示连接池情况 
             showConnNUM();
            
         } catch (ClassNotFoundException ec){
            System.out.println("从自身建立数据库连接时出错;/r/n错误为:" + ec);
         } catch (SQLException e){
            System.out.println("从自身建立数据库连接时出错;/r/n错误为:" + e);
        } catch (Exception et){
            System.out.println("从自身建立数据库连接时出错;/r/n错误为:" + et);
        }
    }

    /** 
     * 生成Access连接 
     * */
    public void createConn(String drv, String url)
    {
        try
{
            /**---------------------------------------------------------------------------------------------------------------**/
            if (connected)
            {
                throw new Exception("数据库已连接,无须重连!");
            }
            Class.forName(drv).newInstance();
            conn = DriverManager.getConnection(url);
            /**---------------------------------------------------------------------------------------------------------------**/
            connected = true;
            /**---------------------------------------------------------------------------------------------------------------**/
            /*控制台显示连接池情况 */
            showConnNUM();
        } catch (ClassNotFoundException ec)
{
            System.out.println("从自身建立数据库连接时出错;/r/n错误为:" + ec);
        } catch (SQLException e){
            System.out.println("从自身建立数据库连接时出错;/r/n错误为:" + e);
        } catch (Exception et){
            System.out.println("从自身建立数据库连接时出错;/r/n错误为:" + et);
        }
    }

    /** 
     * 释放数据库连接 
     * */
    public void releaseConn()
    {
        try{
            /**---------------------------------------------------------------------------------------------------------------**/
            if (!connected)
            {
                throw new SQLException("数据库未连接!");
            }
            if (conn != null)
            {
                /***--------------------------------------------------------------------------------------------------------***/
                // 关闭连接
                conn.close();
                /***--------------------------------------------------------------------------------------------------------***/
                // 标识未连接
                connected = false;
                /***--------------------------------------------------------------------------------------------------------***/
                // 控件台显示连接池情况
                showConnNUM();
            }
        } catch (SQLException e){
            System.out.println("关闭数据库连接时出错;/r/n错误为:" + e);
        }
    }


    /** 
     * 查询记录 
     * @param sql String 查询SQL语句
     *
     * @return ResultSet 返回查询结果集
     * */
    public ResultSet QuerySQL(String sql)
    {
        /**---------------------------------------------------------------------------------------------------------------**/
        // 定义结果集
        ResultSet rs = null;
        /**---------------------------------------------------------------------------------------------------------------**/
        try{
            /***---------------------------------------------------------------------------------------------------------***/
            // 执行SQL 语句, 返回结果集
            pstm = conn.prepareStatement(sql);
            rs   = pstm.executeQuery();
        } catch (SQLException sqle)
{
            System.out.println("执行DataBase::QuerySQL(String)调用SQL语句 " + sql
                    + " 时出错;/r/n错误为:" + sqle);
            if (pstm != null)
            {
                try{
                    pstm.close();
                } catch (Exception e){
                    System.out
                            .println("执行DataBase::QuerySQL(String)试图关闭错误的声明时出错;/r/n错误为:"
                                    + e);
                }
            }
        }
        return rs;
    }

    /** 
     * 执行增删改的语句
     * */
    public int ExecuteSQL(String sql)
    {
        try{
            /**---------------------------------------------------------------------------------------------------------------**/
            pstm = conn.prepareStatement(sql);
            pstm.executeUpdate();
            /**---------------------------------------------------------------------------------------------------------------**/
            conn.commit();
        } catch (SQLException sqle){
            //System.out.println("执行DataBase::ExecuteSQL(String)调用SQL语句 "+sql+"
            // 时出错;/r/n错误为:"+sqle);
            return sqle.getErrorCode();
        } finally{
            try{
                pstm.close();
            } catch (SQLException sqle){
                System.out.println("执行DataBase::ExecuteSQL(String)调用SQL语句 "
                        + sql + " 时出错;/r/n错误为:" + sqle);
            }
        }
        return 0;
    }

    /*
     * 在vector 中 第一项为总页数 第项...个为Hashtable存放列/值
     *  @param1 sql String SQL 语句
     *  @param2 page int 页号
     *  @param3 records int 一页显示条数
     * 
     *  @return vector 指定页显示数据矩阵
     * */
    public Vector getOnePage(String sql, int page, int records)
    {
        return getOnePage(sql, page, records, true);
    }

    /*
     *  在vector 中 第一项为记录数,第二项总页数 第三项后为Hashtable存放列/值
     *  @param1 sql String SQL 语句
     *  @param2 page int 页号
     *  @param3 records int 一页显示条数
     *  @param4 boolean b 
     * 
     *  @return vector 指定页显示数据矩阵
     * */
    public Vector getOnePage(String sql, int page, int records, boolean b)
    {
        Vector vect = new Vector();
        try{
            pstm = conn.prepareStatement(sql);
            rs = pstm.executeQuery();
            /**---------------------------------------------------------------------------------------------------------------**/
            // 记录总数
            int rows = 0;
          
            while (rs.next())
            {
                rows++;
            }
            /**---------------------------------------------------------------------------------------------------------------**/
            // 根据每页显示记录数, 得到总显示页数
            int sum = rows / records;
            if (rows % records != 0 || rows == 0)
            {
                sum++;
            }
            /**---------------------------------------------------------------------------------------------------------------**/
            vect.add("" + rows); // 总记录条数
            vect.add("" + sum);  // 总页数
            /**---------------------------------------------------------------------------------------------------------------**/
            int temp = rows; // 记录总记录数
            /**---------------------------------------------------------------------------------------------------------------**/
            // 移动数据指针, 到当前页所要显示的记录位置
            pstm.close();
            //rs.close();
            /***------------------------------------------------------------------------------------------------------------***/
            pstm = conn.prepareStatement(sql);
            rs = pstm.executeQuery();
            /***------------------------------------------------------------------------------------------------------------***/
            // 把指针定位到当前页第一条记录位置
            rows = (page - 1) * records; 
            rows++ ; // 当前页, 所要显示的记录中, 首条记录的上一条记录的位置

            while (rows > 0)
            {
                rs.next(); // 数据指针, 移到需显示当前页记录的位置
                rows--;
            }
            /**---------------------------------------------------------------------------------------------------------------**/
            // 字符操作类
            DealString ds = new DealString();
            /**---------------------------------------------------------------------------------------------------------------**/
            //查询当前页
            int j = 0; // 记录本页显示的记录数, 递增
            do{
                /***---------------------------------------------------------------------------------------------------------***/
                // 如遇到以下情况, 退出循环
                // 结果集为空 , 已显示记录数等于每页显示的记录数 
                // 总记录数为0 , 需要显示的页号大于总页数
                if (rs == null || j == records || temp == 0 || page > sum)
                {
                    break;
                }
                /***---------------------------------------------------------------------------------------------------------***/
                j++; // 显示的记录条数, 如果等于设定的每页显示记录数, 将退出本循环
                /***---------------------------------------------------------------------------------------------------------***/
                // 列数
                ResultSetMetaData rsmd = rs.getMetaData();
                int cols = rsmd.getColumnCount();
                /***---------------------------------------------------------------------------------------------------------***/
                Hashtable hash = new Hashtable();
                for (int i = 1; i <= cols; i++)
                {
                    // 列名
                    String field = ds.toString(rsmd.getColumnName(i));
                    // 列名对应的值
                    String value = ds.toString(rs.getString(i));
                    // 列名与列值存入哈希表
                    hash.put(field, value);
                }
                /***---------------------------------------------------------------------------------------------------------***/
                // 哈希表存入Vector
                vect.add(hash);
            } while (rs.next());
        } catch (SQLException sqle){
 

热门排行

今日推荐

热门手游