java数据库常用工具类_java 数据库常用工具类

java 数据库常用工具类

在开发中遇到了如果该表调用次数少有的时候整个项目就会调用一次如果这样我们在去创一个Mapper类当Mapper类越来越多该项目看起来是不是太过于臃肿了。所以封装了该类的来进行常用sql语句的调用和分页等功能。希望各位能多多指教

该方法主要是用来对参数进行调用拼接

@Service

public class NrrsSuperDao {

@Autowired

INrrsSuper iSuper ;

/**

*

* @param table 表名

* @param where 字符串的where条件,如果为空,则自动使用and条件将param提供的参数构造where语句

* @param order 排序字段 可以传处类似 id asc 或 id asc,name desc 之类的字符串排序语句

* @param fields 结果中需要的列名,如果为空或空串,则使用 *

* @param page 页码 如果为空,则不分页

* @param size 每页条数 如果为空,则不分页 如果确实需要分页,page size两个参数都必须大于0

* @param param where条件中需要提供的键值对

* @return

* @throws Exception

*/

public ListMapString,Object findAll(String table, String where, String order,String fields, Integer page, Integer size, MapString,Object param)

throws Exception{

HashMapString,Object params = new HashMap() ;

if (table == null || table.equals(""))

throw new Exception("表名不能为空") ;

params.put("table",table) ;

if (where != null !where.equals(""))

params.put("where",where) ;

if (order != null !order.equals(""))

params.put("order",order) ;

if (fields != null !fields.equals(""))

params.put("fields",fields) ;

if (page != null page 0 size != null size 0){

params.put("page",page) ;

params.put("size",size) ;

}

for (String key : param.keySet()){

params.put(key,param.get(key)) ;

}

ListMapString,Object list = iSuper.findAll(params) ;

return listToLowerKey(list) ;

}

/**

*查找记录的总条数

* @param table 表名

* @param where 字符串的where条件,如果为空,则自动使用and条件将param提供的参数构造where语句

* @param fields 结果中需要的列名,如果为空或空串,则使用 *

* @param param where条件中需要提供的键值对

* @return 行数

* @throws Exception

*/

public int findCount(String table,String where,String fields,MapString,Object param) throws Exception{

HashMapString,Object params = new HashMap() ;

if (table == null || table.equals(""))

throw new Exception("表名不能为空") ;

params.put("table",table) ;

if (where != null !where.equals(""))

params.put("where",where) ;

if (fields != null !fields.equals(""))

params.put("fields",fields) ;

for (String key : param.keySet()){

params.put(key,param.get(key)) ;

}

return iSuper.findCount(params) ;

}

/**

* 查找一条记录

* @param table 表名

* @param where 字符串的where条件,如果为空,则自动使用and条件将param提供的参数构造where语句

* @param order 排序字段 可以传处类似 id asc 或 id asc,name desc 之类的字符串排序语句

* @param fields 结果中需要的列名,如果为空或空串,则使用 *

* @param param where条件中需要提供的键值对

* @return

* @throws Exception

*/

public MapString,Object findFirst(String table, String where, String order,String fields, MapString,Object param) throws Exception{

List list = this.findAll(table,where,order,fields,1,1,param) ;

if (list != null list.size() 0){

return (MapString,Object)list.get(0) ;

}

return null ;

}

/**

* 执行一条自定义的select语句

* @param sql sql语句

* @param param where条件中需要提供的键值对

* @return

* @throws Exception

*/

public ListMapString,Object findSql(String sql,MapString,Object param) throws Exception{

MapString,Object params = new HashMap() ;

params.putAll(param);

params.put("sql",sql) ;

ListMapString,Object list = iSuper.findSql(params) ;

return listToLowerKey(list) ;

}

/**

*

* @param table 表名

* @param param 需要插入的值

*/

public void create(String table,MapString,Object param){

MapString,Object params = new HashMap() ;

params.putAll(param);

params.put("table",table) ;

iSuper.save(params);

}

/**

*

* @param table 表名

* @param where 字符串的where条件,如果为空,则自动使用and条件将param提供的参数组成where语句

* @param data 需要更新的字段以及相应的值

* @param param where条件中需要提供的键值对

* @return

* @throws Exception

*/

public int update(String table,String where,MapString,Object data,MapString,Object param)throws Exception{

MapString,Object params = new HashMap() ;

params.put("p",param) ;

if (table == null || table.equals(""))

throw new Exception("表名不能为空") ;

params.put("table",table);

if (where != null !where.equals(""))

params.put("where",where) ;

params.put("d",data) ;

return iSuper.update(params) ;

}

/**

*

* @param table 表名

* @param where 字符串的where条件,如果为空,则自动使用and条件将param提供的参数组成where语句

* @param param where条件中需要提供的键值对

* @return 返回影响的行数

* @throws Exception

*/

public int delete(String table,String where,MapString,Object param)throws Exception{

MapString,Object params = new HashMap() ;

params.putAll(param) ;

if (table == null || table.equals(""))

throw new Exception("表名不能为空") ;

params.put("table",table);

if (where != null !where.equals(""))

params.put("where",where) ;

return iSuper.delete(params) ;

}

private ListMapString,Object listToLowerKey(ListMapString,Object oldlist){

if (oldlist != null oldlist.size() 0){

ListMapString,Object list2 = new ArrayList() ;

for (Object o : oldlist){

MapString,Object row = (MapString,Object)o ;

MapString,Object newrow = new HashMap() ;

for (String key : row.keySet()){

newrow.put(key.toLowerCase(),row.get(key)) ;

}//for

list2.add(newrow) ;

}//for

return list2 ;

}

return oldlist ;

}

}

使用mybatis@SelectProvider注解的机制来对Sql进行编译

@Mapper

@Component

public interface INrrsSuper {

@SelectProvider(type= SuperProvider.class,method = "findall")

ListMapString,Object findAll(MapString, Object param) ;

@SelectProvider(type= SuperProvider.class,method = "findcount")

int findCount(MapString, Object param) ;

@SelectProvider(type=SuperProvider.class,method = "findsql")

ListMapString,Object findSql(MapString, Object param) ;

@InsertProvider(type=SuperProvider.class,method = "save")

void save(MapString, Object data) ;

@UpdateProvider(type = SuperProvider.class,method = "update")

int update(MapString, Object param) ;

@DeleteProvider(type = SuperProvider.class,method = "delete")

int delete(MapString, Object param) ;

}

对参数进行拼接和分页等

public class SuperProvider {

public String findall(MapString,Object param){

StringBuilder sql = new StringBuilder("") ;

String table = param.get("table").toString() ;

String where = param.getOrDefault("where","").toString() ;

String order = param.getOrDefault("order","").toString() ;

String fields = param.getOrDefault("fields","*").toString() ;

Integer page = (Integer) param.getOrDefault("page",0) ;

Integer size = (Integer) param.getOrDefault("size",0) ;

if (fields.equals("") || fields.equals("*"))

fields = "t.*" ;

String[] fieldlist = fields.split("\\,") ;

if (fieldlist != null){

fields = "" ;

for (String f : fieldlist){

f = f.trim() ;

if (!f.equals("") !f.startsWith("t."))

//fields += "t."+f+"," ;

fields += f+"," ;

else

fields += f+"," ;

}//for

fields = fields.replaceAll("\\,$","") ;

}

fields += ",rownum rn " ;

StringBuilder where0 = new StringBuilder("") ;

if (where.equals("")){

for (String key : param.keySet()){

if (key.equals("table") || key.equals("where") || key.equals("order") || key.equals("page") || key.equals("size")|| key.equals("fields"))

continue;

Object val = param.get(key) ;

if (val == null){

where0.append(String.format("and %s is null ",key)) ;

}else{

where0.append(String.format("and %s = #{%s} ",key,key)) ;

}

}//for

where = where0.toString().replaceFirst("and","") ;

}

sql.append("select "+fields+" from "+table) ;

sql.append(" where "+ where) ;

if (!order.equals("")) sql.append(" order by "+order) ;

if (page 0 size 0){

sql.insert(0,"select * from (") ;

sql.append(String.format(") where rn=%d and rn=%d",(page-1)*size+1,(page-1)*size+size)) ;

//sql.append(String.format(" limit %d,%d",(page-1)*size,size)) ;

}

return sql.toString() ;

}

public String findcount(MapString,Object param){

StringBuilder sql = new StringBuilder("") ;

String table = param.get("table").toString() ;

String where = param.getOrDefault("where","").toString() ;

String fields = param.getOrDefault("fields","*").toString() ;

if (fields.equals(""))

fields = "*" ;

StringBuilder where0 = new StringBuilder("") ;

if (where.equals("")){

for (String key : param.keySet()){

if (key.equals("table") || key.equals("order") || key.equals("where") || key.equals("page") || key.equals("size")|| key.equals("fields"))

continue;

Object val = param.get(key) ;

if (val == null){

where0.append(String.format("and %s is null ",key)) ;

}else{

where0.append(String.format("and %s = #{%s} ",key,key)) ;

}

}//for

where = where0.toString().replaceFirst("and","") ;

}

sql.append("select count(0) total from (select "+fields+" from "+table) ;

sql.append(" where "+ where) ;

sql.append(") a") ;

return sql.toString() ;

}

public String findsql(MapString,Object param) throws Exception{

String sql = param.get("sql").toString() ;

return sql ;

}

public String save(MapString,Object data) throws Exception{

String table = data.get("table").toString() ;

StringBuilder sql = new StringBuilder() ;

StringBuilder ins = new StringBuilder() ;

StringBuilder val = new StringBuilder() ;

for (String key : data.keySet()){

if (key.equals("table"))

continue;

ins.append(","+key) ;

val.append(String.format(",#{%s}",key)) ;

}//for

sql.append("insert into "+table+" (")

.append(ins.toString().replaceFirst(",",""))

.append(") values (")

.append(val.toString().replaceFirst(",",""))

.append(")");

return sql.toString() ;

}

public String update(MapString,Object param){

String table = param.get("table").toString() ;

String where = param.getOrDefault("where","").toString() ;

StringBuilder where0 = new StringBuilder("") ;

if (where.equals("")){

MapString,Object pp = (MapString,Object)param.get("p") ;

for (String key : pp.keySet()){

if (key.equals("table") || key.equals("where"))

continue;

Object val = pp.get(key) ;

if (val == null){

where0.append(String.format("and %s is null ",key)) ;

}else{

where0.append(String.format("and %s = #{p.%s} ",key,key)) ;

}

}//for

where = where0.toString().replaceFirst("and","") ;

}

StringBuilder sets = new StringBuilder() ;

MapString,Object data = (MapString,Object)param.get("d") ;

for (String key : data.keySet()){

Object val = data.get(key) ;

if (val == null){

sets.append(String.format(",%s=null",key)) ;

}else{

sets.append(String.format(",%s=#{d.%s}",key,key)) ;

}

}//for

StringBuilder sql = new StringBuilder("update "+table+" set ") ;

sql.append(sets.toString().replaceFirst(",",""))

.append(" where "+where) ;

return sql.toString() ;

}

public String delete(MapString,Object param){

String table = param.get("table").toString() ;

String where = param.getOrDefault("where","").toString() ;

StringBuilder where0 = new StringBuilder("") ;

if (where.equals("")){

for (String key : param.keySet()){

if (key.equals("table") || key.equals("where"))

continue;

Object val = param.get(key) ;

if (val != null){

where0.append(String.format("and %s = #{%s} ",key,key)) ;

}else{

where0.append(String.format("and %s is null ",key)) ;

}

}//for

where = where0.toString().replaceFirst("and","") ;

}

StringBuilder sql = new StringBuilder("delete from "+ table) ;

sql.append(" where "+where) ;

return sql.toString() ;

}

}

java 数据库常用工具类 相关文章

java流程控制学习

流程控制学习 用户交互Scanner 基本语法: Scanner s = new Scanner(System.in); 通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据。 //next()public static void main(Str

java 常用的工具类封装文件类

对于常用的文件操作类进行封装 public static File getFile(String fileName) { try { String path = fileName; File file = new File(path); if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } return file; } catch (Excepti

Hikari配置

/** * [必填]数据库连接地址 */private String jdbcUrl;/** * [必填]数据库连接用户名 */private String username;/** * [必填]数据库连接密码 */private String password;/** * [必填]数据库连接驱动名称 */private String driverClassName;/** * [常用] *

java 常用工具封装日期类

常用的日期类进行封装,避免以后在调用日期的时候在此写该方法那么会导致项目臃肿。 返回当前星期的Map集合 /* * 返回参数所在星期的七天,如传入'2021-06-02'星期四,则返回所在星期周一到周日的Map * @param date * @return Map * */ public static HashMa

思维导图整理Java并发基础

话不多说,先上图。 1、基本概念 欲说线程,必先说进程。 进程 :进程是代码在数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位。 线程 :线程是进程的一个执行路径,一个进程中至少有一个线程,进程中的多个线程共享进程的资源。 操作系统在

SQL 注入-DNS 外带数据

参考文章 数据库DNSLog外带注入-总结 Dnslog在SQL注入中的实战 注:外带数据皆为数据库版本信息 mysql 条件: Windows mysql.ini 中 secure_file_priv 必须为空, select @@secure_file_priv 适用于联合注入或堆叠注入 具体: 利用 mysql (Windows 适用)中的

Mongo 创建索引

打开编辑器 数据库表结构如下 : _id 是数据库保留字段表示主键(创建表的时候自动创建的) 1.执行db.MD5Data.createIndex({"code":-1}) 为code创建索引 -1 标识倒序 1 正序 执行结束后会返回信息 // 1 { "createdCollectionAutomatically": false, "numInde

java中自定义excel模板并且填充内容

场景 读取某一份固定的excel模板,根据数据填充进入指定的位置 本地测试时,在本地resources下创建一个存放模板的位置 例: 实现 挺简单的就直接贴代码吧,不得不吐槽一下博客园的编辑器真的很难用.. @Override public void exportDeposit(UserInfo userInfo, Lo

Java-Apache Commons Jexl3-动态表达式判断

!-- https://mvnrepository.com/artifact/org.apache.commons/commons-jexl3 -- dependency groupIdorg.apache.commons/groupId artifactIdcommons-jexl3/artifactId version3.1/version /dependency /** * Jexl表达式计算 */ @Test public void jexlUseFun(

【Java】String字符串格式化

一、前言 String.format() 作为文本处理工具,为我们提供强大而丰富的字符串格式化功能,为了不止步于简单调用 String.format("Hello %s", "John"); ,下面将笔记整理并记录下来。 其实各个语言的字符串格式化方法都是相通的,你可以在其中找到你熟悉的语言

package com.hexiang.utils.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.apache.log4j.Logger; public class DBConnection { /** * 获得与数据库的连接 * * @param path * @return Connection */ public static Connection getConn(String classDriver, String url, String user, String pwd) { try { Class.forName(classDriver); return DriverManager.getConnection(url, user, pwd); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } public static Connection getConn(DataSource dataSource) { try { return dataSource.getConnection(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } public static Connection getConn(String jndiName) { try { Context ctx; ctx = new InitialContext(); DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/" + jndiName); return dataSource.getConnection(); } catch (NamingException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } public static Connection getConn(Properties properties) { try { String driver = properties.getProperty("jdbc.driverClassName"); String url = properties.getProperty("jdbc.url"); String user = properties.getProperty("jdbc.username"); String password = properties.getProperty("jdbc.password"); Class.forName(driver); return DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } /** * oracle连接 * * @param path * @return Connection */ public static Connection getOracleConn(String
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、付费专栏及课程。

余额充值