Package com.lingbobu.flashdb.transfer.sqlfunc

Source Code of com.lingbobu.flashdb.transfer.sqlfunc.DbUtil

package com.lingbobu.flashdb.transfer.sqlfunc;

import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
import javax.sql.DataSource;

import com.lingbobu.flashdb.common.DataTypes;
import com.lingbobu.flashdb.common.QueryResultSet;
import com.lingbobu.flashdb.common.FlashDatabase;
import com.lingbobu.flashdb.jdbc.Utils;

/**
* 常用数据库查询函数封装
*/
public class DbUtil {
 
  public DbUtil(DataSource flashdbDataSource) {
    this.flashDatabase = Utils.dataSource2flashdb(flashdbDataSource);
  }

  private FlashDatabase flashDatabase;
 
  public Object queryForObject(String sql) {
    QueryResultSet qrs = flashDatabase.executeQuery(sql, new Object[0]);
    if (qrs.getColumnCount() != 1)
      throw new RuntimeException("Result of queryForObject(...) must be only one column.");
    if (qrs.getRowCount() > 1)
      throw new RuntimeException("Result of queryForObject(...) must be only one row.");
    if (qrs.getRowCount() == 0)
      return null;
    else
      return qrs.fastGetValue(0, 0);
  }
 
  public Set<Object> queryForSet(String sql) {
    QueryResultSet qrs = flashDatabase.executeQuery(sql, new Object[0]);
    if (qrs.getColumnCount() != 1)
      throw new RuntimeException("Result of queryForSet(...) must be only one column.");
    Set<Object> result = new HashSet<Object>();
    for (int i=0; i < qrs.getRowCount(); i++) {
      Object value = qrs.fastGetValue(i, 0);
      if (value == null) continue;
      result.add(value);
    }
    return result;
  }
 
  /**
   * 返回当前时间
   * @return
   */
  public static Timestamp now() {
    return new Timestamp(System.currentTimeMillis());
  }
 
  /**
   * 时间格式转换
   * @param t
   * @return
   */
  public static long time2long(Timestamp t) {
    return t.getTime();
  }
 
  public static Timestamp str2time(String str) {
    return DataTypes.parseTimestamp(str);
  }
 
  /**
   * 参数查询(为方便在GUI工具中执行类似SYSCALL DbUtil.query('...', ...))的参数计算查询
   * @return
   */
  public QueryResultSet query(String sql, Object param1) {
    return flashDatabase.executeQuery(sql, new Object[]{param1});
  }
 
  public QueryResultSet query(String sql, Object param1, Object param2) {
    return flashDatabase.executeQuery(sql, new Object[]{param1, param2});
  }
 
  public QueryResultSet query(String sql, Object param1, Object param2, Object param3) {
    return flashDatabase.executeQuery(sql, new Object[]{param1, param2, param3});
  }
}
TOP

Related Classes of com.lingbobu.flashdb.transfer.sqlfunc.DbUtil

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.