您的位置:首页 > 编程语言 > Java开发

数据库操作通用类 DataBase.java

2007-04-13 02:56 447 查看
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 : 否
方法简介
[align=center]序号[/align]
[align=center]方法名[/align]
[align=center]参数[/align]
[align=center]返回值[/align]
[align=center]功能[/align]
[align=center]1[/align]
DataBase

Void
构造函数
[align=center]2[/align]
showConnNum

Void
在控件台显示当前连接池情况,连接数,总连接数等信息
[align=center]3[/align]
getConnPool

Void
* 取得Tomcat连接池, 在server.xml 中配置的连接池
* 从连接池中取得连接
[align=center]4[/align]
getMyConnPool

Void
* 创建连接池, 并取得连接
* 从由连接池类DBConnectionManager 创建的连接池
[align=center]5[/align]
releaseMyConnPool

Boolean
释放我的连接池, 即由DBConnectionManager 创建的连接池
[align=center]6[/align]
createConn
String drv
String url
String usr
String pwd
Void
* 生成Oracle SQLServer 等的连接
* 不使用连接池
[align=center]7[/align]
createConn
String drv
String url
Void
生成Access连接
[align=center]8[/align]
realaseConn

Void
释放的是当前类中, 通过各种方法取得的连接
[align=center]9[/align]
QuerySql
<
23ff7
span style="FONT-SIZE: 9pt">String sql
ResultSet
执行查询sql 语句, 并返回执行结果
[align=center]10[/align]
ExceuteSql
String sql
Int
执行删除sql 语句, 自动提交, 成功返回0,失败返回错误代码
[align=center]11[/align]
getOnePage
String sql
int page
int records
Vector
执行查询sql 语句
将页号为page , 每页显示records条记录的结果集,以键/值对应的形式存入Hashtable 并存入Vector
[align=center]12[/align]
getOnePage1
String sql
int page
int records
Boolean b
Vector
执行查询sql 语句
将页号为page , 每页显示records条记录的结果集,以键/值对应的形式存入Hashtable 并存入Vector
[align=center]13[/align]
getOnePage
String sql
int page
int records boolean useDic
Vector
执行查询sql 语句
将页号为page , 每页显示records条记录的结果集,以键/值对应的形式存入Hashtable 并存入Vector
如果useDic 为true , 从配置表中取每面显示记录数
[align=center]14[/align]
getData
String sql
Vector
执行查询sql 语句
将结果以 列/值对应的存入Hashtabl中, 存入Vector
[align=center]15[/align]
QueryClob
String table String wherestr
String clobfield
String
查询 Clob型字段的值
将Clob结果转换为String , 并返回String
[align=center]16[/align]
UpdateClob
String table String wherestr
String clobfield
String clobvalue
Int
将clobvalue 转换为clob
用转换后的clob 更新clobfield字段
成功返回0 , 失败返回错误代码
[align=center]17[/align]
QueryBlob
String table String wherestr String blobfield
String
查询 Blob 型字段的值
将Blob 结果转换为String , 并返回String
[align=center]18[/align]
UpdateBlob
String table String wherestr
String blobfield String blobvalue
Int
将blobvalue 转换为blob
用转换后的blob 更新blobfield字段
成功返回0 , 失败返回错误代码
[align=center]19[/align]
QueryBLOB_JNDI
String table String wherestr String blobfield
String
查询blob 型字段, 返回String
[align=center]20[/align]
UpdateBLOB_JNDI
String table String wherestr String blobfield String blobvalue
Int
更新blob 型辽段
[align=center]21[/align]
clobInsert
String sql String table String wherestr
String clobfield String infile
Int
往数据库中插入一个新的CLOB对象
sql 是一条插入语句
[align=center]22[/align]
clobModify
String table String wherestr String clobfield
String infile
int
修改CLOB对象(是在原CLOB对象基础上进行覆盖式的修改)
[align=center]23[/align]
clobReplace
String table String wherestr String clobfield
String infile
Int
替换CLOB对象(将原CLOB对象清除,换成一个全新的CLOB对象)
[align=center]24[/align]
blobInsert
String sql String table String wherestr
String blobfield
String infile
int
向数据库中插入一个新的BLOB对象
[align=center]25[/align]
blobModify
String table String wherestr String blobfield
String infile
int
修改BLOB对象(是在原BLOB对象基础上进行覆盖式的修改)
[align=center]26[/align]
blobReplace
String table String wherestr String blobfield
String infile
int
替换BLOB对象(将原BLOB对象清除,换成一个全新的CLOB对象)
[align=center]27[/align]
getDataBaseInfo
Hashtable
数据库信息(类型,版本,驱动等) 使用DatabaseMetaData类
[align=center]28[/align]
getTableList
Vector
使用DatabaseMetaData类的getTables
[align=center]29[/align]
getTableStruct
String table
Vector
数据表的结构(字段名,类型,是否为空,精度等) DatabaseMetaData类
[align=center]30[/align]
getResultSetData
ResultSet rs
Vector
列/值 存入Hashtable, 将Hashtable 存入Vector中
[align=center]31[/align]
prepareStatement
String sql
Void
用sql 创建表达, 为类变量pstm 赋值
[align=center]32[/align]
executeQuery

void
执行查询, 执行变量pstm中设置的表达, 返回结果集赋给类变量rs
[align=center]33[/align]
next

boolean
调用rs.next(), 转向下一条记录
[align=center]34[/align]
getObject
String field String sqlType
String
取得数据并根据数据类型转化为字符串
[align=center]35[/align]
setObject
int index
String value
String sqlType
Void
根据数据类型保存到数据库
根据将参数sqlType 将value 转换为相应的类型
调用 psmt.setObject(index, 转换后的value)
[align=center]36[/align]
executeUpdate

Void
调用 psmt.executeUpdate() , 执行数据更新
[align=center]37[/align]
closePstm

Void
调用 psmt.close(), 关闭表达对象
[align=center]38[/align]
closeRs

Void
调用 rs.close(), 关闭结果集
[align=center]39[/align]
setBinaryStream
int index InputStream is int t
Void
调用 pstm.setBinaryStream(index, is, t);
[align=center]40[/align]
setAsciiStream
int index InputStream is int t
Void
调用 pstm.setBinaryStream(index, is, t);
[align=center]41[/align]
getAutoCommit
boolean
调用conn.getAutoCommit(); 判断是否自动提交
[align=center]42[/align]
closeAutoCommit
Void
调用 conn.setAutoCommit(false);
[align=center]43[/align]
commit
Void
调用 conn.commit()
[align=center]44[/align]
Rollback
Void
调用 conn.rollback()
[align=center]45[/align]
openAutoCommit
Void
调用 conn.setAutoCommit(true)
[align=center]46[/align]
createStatement
Void
调用 stm = conn.createStatement();
[align=center]47[/align]
clearBatch
void
调用 stm.clearBatch();
[align=center]48[/align]
addBatch
Void
调用 stm.addBatch(sql);
[align=center]49[/align]
executeBatch
Int[]
调用 stm.executeBatch();
[align=center]50[/align]
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; // 记录本页显示的记录数, 递增
[b] 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){
System.out.println("执行SQL语句 " + sql + " 分页至第 " + page
+ " 页时出错;错误为:" + sqle);
} finally{
closeRs();
closePstm();
}
return vect;
}

/*
* @param1 sql String SQL 语句
* @param2 page int 页号
* @param3 records int 一页显示条数
* @param4 useDic boolean 是否使用配置表中设定的每页显示记录数
* @return vector 指定页显示数据矩阵
* 在vector 中 第一项为总页数 第项...个为Hashtable存放列/值
*
* 分页是返回一页的数据矩阵
*/
public Vector getOnePage1(String sql, int page, int records, boolean useDic)
{
/**---------------------------------------------------------------------------------------------------------------**/

Vector vect = new Vector();
/**---------------------------------------------------------------------------------------------------------------**/

int zdrecords = records;
/**---------------------------------------------------------------------------------------------------------------**/

try{
if (useDic)
{
/***------------------------------------------------------------------------------------------------------***/
// 从配置表中读取每页显示记录数
String strsql = "select XMMC from CODE_ZDB where trim(ZDMC)='每页显示记录条数'";
pstm = conn.prepareStatement(strsql);
rs = pstm.executeQuery();
/***------------------------------------------------------------------------------------------------------***/
if (rs.next())
{
zdrecords = Integer.parseInt(rs.getString("XMMC"));
}
/***------------------------------------------------------------------------------------------------------***/
rs.close();
pstm.close();
}

//查询总页数
// pstm.clearBatch();
pstm = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
&nb
2559f
sp; ResultSet.CONCUR_UPDATABLE);
rs = pstm.executeQuery();
/***---------------------------------------------------------------------------------------------------------***/

// 总记录数
int rows = 0;
while (rs.next())
{
rows++;
}
int sum = rows / zdrecords;
if (rows % zdrecords != 0 || rows == 0)
{
sum++;
}
/***---------------------------------------------------------------------------------------------------------***/

vect.add("" + sum); // 添加总页数到Vector 中
/***---------------------------------------------------------------------------------------------------------***/

rs.close();
pstm.close();
/***---------------------------------------------------------------------------------------------------------***/
// 得到结果集, 以可移动指针的模式
// pstm.clearBatch();
pstm = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = pstm.executeQuery();

// 计算显示页的首记录的位置
rows = (page - 1) * zdrecords;
/***---------------------------------------------------------------------------------------------------------***/

// 移动指针位置到首记录
rs.absolute(rows + 1);
rs.previous();
/***---------------------------------------------------------------------------------------------------------***/

DealString ds = new DealString();
/***---------------------------------------------------------------------------------------------------------***/

// 查询当前页
int j = 0;
while (rs.next())
{
/****---------------------------------------------------------------------------------------------------****/
if (j == zdrecords)
{
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);
}
/****---------------------------------------------------------------------------------------------------****/
vect.add(hash);
}
} catch (SQLException sqle){
System.out.println("DataBase::getOnePage(String,int,int)执行SQL语句 "
+ sql + " 分页至第 " + page + " 页时出错;错误为:" + sqle);
} finally{
if (rs != null)
{
try{
rs.close();
} catch (SQLException e){
System.out
.println("DataBase::getOnePage(String,int,int)调用SQL语句 "
+ sql + " 时出错;/r/n错误为:" + e);
}
}
if (pstm != null)
{
try{
pstm.close();
} catch (SQLException e){
System.out
.println("DataBase::getOnePage(String,int,int)调用SQL语句 "
+ sql + " 时出错;/r/n错误为:" + e);
}
}
}
return vect;
}


/*
* @param1 sql String SQL语句
*
* @return Vector 存储对象为Hashtabl, 语句结果集对应的矩阵
*
* 返回SQL 语句执行后所得结果集, 存储为Hashtable 形式的vector 对象
* */
public Vector getData(String sql)
{
Vector vect = new Vector();
try{
/**---------------------------------------------------------------------------------------------------------------**/
pstm = conn.prepareStatement(sql);
rs = pstm.executeQuery();
/**---------------------------------------------------------------------------------------------------------------**/
DealString ds = new DealString();
/**---------------------------------------------------------------------------------------------------------------**/
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
/**---------------------------------------------------------------------------------------------------------------**/
while (rs.next())
{
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);
}
/***--------------------------------------------------------------------------------------------------------***/
vect.add(hash);
/***--------------------------------------------------------------------------------------------------------***/
}
} catch (SQLException sqle){
System.out.println("执行DataBase::getData(String)执行SQL语句 " + sql
+ " 时出错;错误为:" + sqle);
} finally{
if (rs != null)
{
try{
rs.close();
} catch (SQLException e){
System.out
.println("执行DataBase::getData(String)试图释放rs时出错;/r/n错误为:"
+ e);
}
}
if (pstm != null)
{
try{
pstm.close();
} catch (SQLException e){
System.out
.println("执行DataBase::getData(String)试图释放pstm时出错;/r/n错误为:"
+ e);
}
}
}
return vect;
}
/**
* 查询BLOB类型值
*
* @param1 table String 表名
* @param2 wherestr String 条件
* @param3 blobfield String blob类型字段
*
* @return String blob转换成string 返回
* */
public String QueryBLOB(String table, String wherestr, String blobfield)
{
String out = "";
try{
String sqlCommand = "select " + blobfield + " from " + table;
if (!wherestr.equals(""))
{
sqlCommand = sqlCommand + " where " + wherestr;
}
pstm = conn.prepareStatement(sqlCommand);
rs = pstm.executeQuery();
if (rs.next())
{
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(blobfield);
if (blob != null)
{
InputStream is = blob.getBinaryStream();
InputStreamReader isw = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isw);
String s = br.readLine();
while (s != null)
{
out += s;
s = br.readLine();
}
}
}
out = (new DealString()).Replace(out, "/"", "/"/"");
} catch (SQLException sqle) {
System.out.println("调用MyDataBase.QueryBLOB()函数错误:/r/n" + sqle);
} catch (IOException iosql){
System.out.println("调用MyDataBase.QueryBLOB()函数错误:/r/n" + iosql);
} finally{
if (rs != null)
{
try{
rs.close();
} catch (SQLException e){
System.out.println("试图释放rs时出错;/r/n错误为:" + e);
}
}
if (pstm != null)
{
try{
pstm.close();
} catch (SQLException e){
System.out.println("试图释放pstm时出错;/r/n错误为:" + e);
}
}
}
return out;
}

/**
* 修改BLOB类型值
* @param1 table String 表名
* @param2 wherestr String 条件
* @param3 blobfield String blob 字段名
* @param4 blobvalue String string形式的blob 值
*
* @return int 成功返回0, 失败返回错误代码
* */
public int UpdateBLOB(String table, String wherestr, String blobfield, String blobvalue)
{
try{
/**---------------------------------------------------------------------------------------------------------------**/

/* 设定不自动提交 */
boolean defaultCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
/**---------------------------------------------------------------------------------------------------------------**/

/* 清空原BLOB对象 */
String sqlCommand = "UPDATE " + table + " set " + blobfield + "=EMPTY_BLOB()";
if (!wherestr.equals(""))
{
sqlCommand += " where " + wherestr;
}
pstm = conn.prepareStatement(sqlCommand);
pstm.executeUpdate();
/**---------------------------------------------------------------------------------------------------------------**/

/* 查询BLOB对象并锁定 */
sqlCommand = "select " + blobfield + " from " + table;
if (!wherestr.equals(""))
{
sqlCommand += " where " + wherestr;
}
sqlCommand += " for update";
pstm.clearBatch();
pstm.addBatch(sqlCommand);
rs = pstm.executeQuery();

while (rs.next())
{
/***--------------------------------------------------------------------------------------------------------***/
/* 获取此BLOB对象 */
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(blobfield);
BufferedOutputStream out = new BufferedOutputStream(blob.getBinaryOutputStream());
byte b[] = blobvalue.getBytes();
out.write(b, 0, b.length);
}
/**-----------------------------------------------------------**/
/* 正式提交 */
conn.commit();
conn.setAutoCommit(defaultCommit);
} catch (SQLException sqle){
System.out.println("调用MyDataBase.UpdateBLOB()函数错误:/r/n" + sqle);
return sqle.getErrorCode();
} catch (Exception e){
System.out.println("调用MyDataBase.UpdateBLOB()出错:" + e);
} finally{
if (rs != null)
{
try{
rs.close();
} catch (SQLException e){
System.out
.println("调用MyDataBase.UpdateBLOB()试图释放rs时出错;/r/n错误为:"
+ e);
}
}
if (pstm != null)
{
try{
pstm.close();
} catch (SQLException e){
System.out
.println("调用MyDataBase.UpdateBLOB()试图释放pstm时出错;/r/n错误为:"
+ e);
}
}
}
return 0;
}

/**
* 修改BLOB对象(是在原BLOB对象基础上进行覆盖式的修改)
* */
public int blobModify(String table, String wherestr, String blobfield, String infile)
{
try{
/* 设定不自动提交 */
boolean defaultCommit = conn.getAutoCommit();
conn.setAutoCommit(false);

/* 查询此BLOB对象并锁定 */
String sqlCommand = "select " + blobfield + " from " + table;
if (!wherestr.equals(""))
{
sqlCommand += " where " + wherestr;
}
sqlCommand += " for update ";
pstm = conn.prepareStatement(sqlCommand);
rs = pstm.executeQuery();

while (rs.next())
{
/* 取出此BLOB对象 */
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(blobfield);

/* 进行覆盖式修改 */
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(infile));
BufferedOutputStream out = new BufferedOutputStream(blob
.getBinaryOutputStream());

int c;
while ((c = in.read()) != -1)
{
out.write(c);
}

in.close();
out.close();
}
rs.close();
pstm.close();

/* 正式提交 */
conn.commit();

/* 恢复原提交状态 */
conn.setAutoCommit(defaultCommit);
} catch (SQLException sqle){
System.out.println("调用DataBase.blobModify()函数错误:/r/n" + sqle);
return sqle.getErrorCode();
} catch (IOException iosql){
System.out.println("调用DataBase.blobModify()函数错误:/r/n" + iosql);
}
return 0;
}

/**
* 替换BLOB对象(将原BLOB对象清除,换成一个全新的BLOB对象)
* */
public int blobReplace(String table, String wherestr, String blobfield, String infile)
{
int out = 0;
try{
/* 设定不自动提交 */
boolean defaultCommit = conn.getAutoCommit();
conn.setAutoCommit(false);

/* 清空原BLOB对象 */
String sqlCommand = "update " + table + " set " + blobfield + "=EMPTY_BLOB()";
if (!sqlCommand.equals(""))
{
sqlCommand += " where " + wherestr;
}
pstm = conn.prepareStatement(sqlCommand);
pstm.executeUpdate();
pstm.close();

/* 正式提交 */
conn.commit();

/* 恢复原提交状态 */
conn.setAutoCommit(defaultCommit);

// 执行修改
out = blobModify(table, wherestr, blobfield, infile);
} catch (SQLException sqle) {
System.out.println("调用DataBase.blobReplace()函数错误:/r/n" + sqle);
return sqle.getErrorCode();
}
return out;
}

/**
* 数据库信息
* */
public Hashtable getDataBaseInfo()
{
Hashtable hash = new Hashtable();
try{
DatabaseMetaData dmd = conn.getMetaData();


hash.put("1", dmd.getCatalogSeparator());
hash.put("2", dmd.getCatalogTerm());
hash.put("数据库类型名称", dmd.getDatabaseProductName());
hash.put("数据库版本", dmd.getDatabaseProductVersion());
hash.put("5", dmd.getDefaultTransactionIsolation() + "");
hash.put("驱动版本(最大)", dmd.getDriverMajorVersion() + "");
hash.put("驱动版本(最小)", dmd.getDriverMinorVersion() + "");
hash.put("驱动名", dmd.getDriverName());
hash.put("驱动版本", dmd.getDriverVersion());
hash.put("10", dmd.getExtraNameCharacters());
hash.put("11", dmd.getIdentifierQuoteString());
hash.put("12", dmd.getMaxBinaryLiteralLength() + "");
hash.put("最大行限定", dmd.getMaxRowSize() + "");
hash.put("方案", dmd.getSchemaTerm());
hash.put("日期函数", dmd.getTimeDateFunctions());
hash.put("连接地址", dmd.getURL());
hash.put("用户名", dmd.getUserName());
} catch (SQLException sqle){
System.out.println("调用DataBase.getDataBaseInfo()函数错误:/r/n" + sqle);
} catch (AbstractMethodError e){
System.out.println("调用DataBase.getDataBaseInfo()函数错误:/r/n" + e);
}
return hash;
}

/**
* 数据表列表
* */
public Vector getTableList()
{
Vector vect = new Vector();
try{
if (ParentBean.DBType.equals("Access"))
{
//ExecuteSQL("create table tab(name char)");
//ExecuteSQL("insert into tab(name) select name from MsysObjects");
rs = QuerySQL("select name as TABLE_NAME from tab");
//rs = QuerySQL("SELECT MSysObjects.Name as TABLE_NAME

// FROM MsysObjects WHERE (Left$([Name],1)<>'~')
// AND (Left$([Name],4) <> 'Msys')
// AND (MSysObjects.Type)=1
// ORDER BY MSysObjects.Name");
}else{
DatabaseMetaData dmd = conn.getMetaData();
String[] types = new String[1];
types[0] = "TABLE";
//types[1] = "VIEW"
rs = dmd.getTables(null, ParentBean.DBName.toUpperCase(), "%", types);
}
System.out.println("000" + getResultSetData(rs));
while (rs.next())
{
vect.add((new DealString()).toString(rs.getString("TABLE_NAME")));
}
rs.close();
} catch (SQLException sqle){
System.out.println("调用DataBase.getTableList()函数错误:/r/n" + sqle + sqle.getErrorCode());
} catch (AbstractMethodError e){
System.out.println("调用DataBase.getTableList()函数错误:/r/n" + e);
}
return vect;
}

/**
* 数据表的结构
* */
public Vector getTableStruct(String table)
{
Vector vect = new Vector();
try{
/*
* rs = QuerySQL("select * from "+table);

* ResultSetMetaData rmd =rs.getMetaData();
* int cols = rmd.getColumnCount();
* for(int i=1;i <=cols;i++)
* {
* Hashtable hash = new Hashtable();
* //hash.put("目录名",rmd.getCatalogName(i));
* //hash.put("列返回值类型名",rmd.getColumnClassName(i));
* hash.put("列定义大小",rmd.getColumnDisplaySize(i)+"");
* //hash.put("列标签",rmd.getColumnLabel(i));
* hash.put("字段名",rmd.getColumnName(i));
* hash.put("列类型编号",rmd.getColumnType(i)+"");
* hash.put("列标准类型名",rmd.getColumnTypeName(i));
* hash.put("列精确度",rmd.getPrecision(i)+"");
* //hash.put("10",rmd.getScale(i)+"");
* //hash.put("11",rmd.getSchemaName(i));
* //hash.put("表名",rmd.getTableName(i));
* //hash.put("13",rmd.isAutoIncrement(i)+"");
* //hash.put("大小写敏感",rmd.isCaseSensitive(i)+"");
* //hash.put("是否为金额",rmd.isCurrency(i)+"");
* //hash.put("是否可写",rmd.isDefinitelyWritable(i)+"");
* hash.put("是否可为空",rmd.isNullable(i)+"");
* //hash.put("是否只读",rmd.isReadOnly(i)+"");
* //hash.put("是否可查询",rmd.isSearchable(i)+"");
* hash.put("是否数字",rmd.isSigned(i)+"");
* //hash.put("是否可写",rmd.isWritable(i)+""); vect.add(hash); }
*/

DatabaseMetaData dmd = conn.getMetaData();
rs = dmd.getColumns(null, ParentBean.DBName.toUpperCase(), table.toUpperCase(), null);
rs = dmd.getColumns(null, "HG", "TEST", null);
ResultSetMetaData rmd = rs.getMetaData();
int cols = rmd.getColumnCount();
System.out.println(cols + "gggHHH");
System.out.println("ResultSet" + getResultSetData(rs));
while (rs.next())
{
System.out.println("TTTTT");
Hashtable hash = new Hashtable();
hash.put("列定义大小", rs.getString("CHAR_OCTET_LENGTH") + "");
String f = rs.getString("COLUMN_NAME");
ResultSet r = QuerySQL("select " + f + " from " + table);
ResultSetMetaData rm = r.getMetaData();

hash.put("字段名", f + "");
hash.put("列类型编号", rm.getColumnType(1) + "");
hash.put("列标准类型名", rm.getColumnTypeName(1) + "");

hash.put("是否可为空", rm.isNullable(1) + "");
hash.put("是否数字", rm.isSigned(1) + "");
hash.put("列定义大小", rm.getColumnDisplaySize(1) + "");
hash.put("列精确度", rs.getString("NUM_PREC_RADIX") + "");

r.close();
Statement stst = r.getStatement();
if (stst != null)
stst.close();
vect.add(hash);
}
Statement stmt = rs.getStatement();
rs.close();
if (stmt != null)
stmt.close();
System.out.println("____" + vect);
} catch (SQLException sqle){
System.out.println("调用DataBase.getTableStruct()函数错误:/r/n" + sqle);
} catch (AbstractMethodError e){
System.out.println("调用DataBase.getTableStruct()函数错误:/r/n" + e);
}
return vect;
}

/**
* 取得数据集内容
* */
public Vector getResultSetData(ResultSet rs)
{
Vector vect = new Vector();
try{
//取得列数和列名
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
while (rs.next())
{
Hashtable hash = new Hashtable();
for (int i = 1; i <= cols; i++)
{
DealString ds = new DealString();
String field = ds.toString(rsmd.getColumnName(i));
String value = ds.toString(rs.getString(i));
hash.put(field, value);
}
vect.add(hash);
}
} catch (SQLException sqle){
System.out.println("调用DataBase.getResultSetData()函数错误:/r/n" + sqle);
}
return vect;
}

/**
* 创建申明对象
* */
public void prepareStatement(String sql)
{
try{
pstm = conn.prepareStatement(sql);
} catch (SQLException sqle){
System.out.println("调用DataBase.prepareStatement()函数错误:/r/n" + sqle);
}
}

/**
* 执行查询
* */
public void executeQuery()
{
try{
rs = pstm.executeQuery();
} catch (SQLException sqle){
System.out.println("调用DataBase.executeQuery()函数错误:/r/n" + sqle);
}
}

/**
* 转向下一条
* */
public boolean next()
{
try{
return rs.next();
} catch (SQLException sqle){
System.out.println("调用DataBase.next()函数错误:/r/n" + sqle);
}
return true;
}

/**
* 执行更新
* */
public void executeUpdate()
{
try{
pstm.executeUpdate();
} catch (SQLException sqle){
System.out.println("调用DataBase.executeUpdate()函数错误:/r/n" + sqle);
}
}

/**
* 关闭申明对象
* */
public void closePstm()
{
if (pstm != null)
try{
pstm.close();
} catch (SQLException sqle){
System.out.println("调用DataBase.closePstm()函数错误:/r/n" + sqle);
}
}

/**
* 关闭游标
* */
public void closeRs()
{
if (rs != null)
try{
rs.close();
} catch (SQLException sqle){
System.out.println("调用DataBase.closeRs()函数错误:/r/n" + sqle);
}
}

/**
* 得到是否自动提交
*/
public boolean getAutoCommit()
{
try {
return conn.getAutoCommit();
} catch (SQLException e){
}
return true;
}

/**
* 关闭自动提交
*/
public void closeAutoCommit()
{
try{
conn.setAutoCommit(false);
} catch (SQLException e){
}
}

/**
* 提交操作
**/
public void commit()
{
try{
conn.commit();
} catch (SQLException e){
}
}

/**
* 执行回滚
**/
public void rollback()
{
try{
conn.rollback();
} catch (SQLException e){
}
}

/**
* 设置自动回滚
*/
public void openAutoCommit()
{
try{
conn.setAutoCommit(true);
} catch (SQLException e){
}
}

/**
* 创建statement 对象
**/
public void createStatement()
{
try{
stm = conn.createStatement();
} catch (SQLException e){
}
}

/**
* 清空批处理
*/
public void clearBatch()
{
try{
stm.clearBatch();
} catch (SQLException e){
}
}

/**
* 增加批处理
*/
public void addBatch(String sql)
{
try{
stm.addBatch(sql);
} catch (SQLException e){
}
}

/**
* 执行批处理
**/
public int[] executeBatch()
{
try{
return stm.executeBatch();
} catch (SQLException e){
}
return null;
}

/**
* 关闭statement 对象
**/
public void closeStm()//专门使用
{
if (stm != null)
try{
stm.close();
} catch (SQLException e){
}
}

/**
* 测试是否连接
*/
public String ttest() throws Exception
{
PreparedStatement pstm = conn.prepareStatement("select * from test1");
ResultSet rs = pstm.executeQuery();
rs.next();
InputStream is = rs.getBinaryStream("ziduan");
Statement stmt = rs.getStatement();
rs.close();
if (stmt != null)
stmt.close();
return (new DealFile()).readCHStr(is);
}


public static void main(String args[]) throws Exception
{
/*
* 必须执行的代码 stm = rs.getStatement(); rs.close(); stm.close();
*/
System.out.println("begin/r/n/r/n");

DataBase db = new DataBase();
db.createConn("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@10.0.0.94:1521:hg", "oaadminuser",
"lancom4454");
//db.createConn("sun.jdbc.odbc.JdbcOdbcDriver","jdbc:odbc:test");
//db.createConn("com.microsoft.jdbc.sqlserver.SQLServerDriver","jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test","test","test");
//ParentBean.DBName = "hg";

//System.out.println(db.UpdateCLOB("test","","content","ttew测试tewagdsagsad"));
//System.out.println(db.QueryCLOB("test","","content"));

//System.out.println(db.getDataBaseInfo());
//System.out.println(db.getTableList());
//System.out.println(db.getTableStruct("test"));
//System.out.println(db.getResultSetData(db.QuerySQL("select * from
// test")));
//System.out.println(db.getResultSetData(db.getTypeInfo()));

/**
* ????? 1.Access不能取得表列表 2.Oracle不能取得表结构:CLOB,BLOB 3.不能取得视图结构
* 4.clob,blob,time类型读出和写入时没有区分,都当作字符串处理了 5.字段精确度问题?如何区分和使用?
* 6.定义不同数据库的需求, 7.可视化的界面 8.字段映射列表,如何更合理?
*
* 1。字段类型,创建表时字段属性写法(长度,精确度,),写入数据时所用的函数setObject
* clob,blob,字符串(Ascii,unicode),数字(整数,浮点数),时间,布尔型,字节类型,数组
* 2。如何取得access表列表 3。数据库驱动,不同数据库,字段映射配置情况 4。对不同的数据实现不同的配置选项,仿造SQLServer
*
*/
/*
* //不用addBatch(),clearBatch() //str长度 <=file长度-2
* //间接方式----------------(1) db.prepareStatement("update test set
* dlxc=?"); db.setObject(1,"大类型测试","CLOB"); db.executeUpdate();
* db.closePstm(); //---------------------- db.prepareStatement("select *
* from test"); db.executeQuery(); db.next();
* System.out.println(db.getObject("dlxc","CLOB")); db.closeRs();
* db.closePstm();
*
* //直接方式---------------------(2) db.prepareStatement("update test set
* dlxc = ? "); FileInputStream fis = new FileInputStream("out.txt");
* db.setAsciiStream(1,fis,100); db.executeUpdate();
* //----------------------
* System.out.println(db.QueryCLOB("test","","dlxc"));
*
*/
//db.ExecuteSQL("create table test1 (bh integer,ziduan blob)");
//db.ExecuteSQL("insert into test1(bh) values(1)");
/*
* db.prepareStatement("update test1 set ziduan=?");
* db.setObject(1,"大类型测试","BLOB"); db.executeUpdate(); db.closePstm();
*
* db.prepareStatement("select * from test1"); db.executeQuery();
* db.next(); System.out.println(db.getObject("ziduan","BLOB"));
*
* db.closeRs(); db.closePstm();
*/
//System.out.println(db.ttest());

//db.prepareStatement("update article set content=?");
//db.setObject(1,"大类型测试eee","BLOB");
//db.executeUpdate();
//db.closePstm();
//db.UpdateBLOB_JNDI("test1","bh=1","ziduan","大类型测试333");
//System.out.println(db.QueryBLOB_JNDI("article","id=60","content"));
System.out
.println(db.makeID("ZZ_GRWJB", "ZGBH", "WJBH", "2340", false));
db.releaseConn();
System.out.println("/r/n/r/nend");
}
}

[/b]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息