jdbc连接示例

示例一

public ArrayList readData(String sqlCommand)throws Exception {
  // TODO Auto-generated method stub
  //return null;
  ArrayList dataList = new ArrayList();

  if (sqlCommand != null && sqlCommand != "") {
   Connection conn = null;
   Statement statement = null;
   ResultSet rs = null;
   try {
    Class.forName("oracle.jdbc.driver.OracleDriver")
      .newInstance();
    conn = DriverManager.getConnection(this.url, this.username,
      this.password);
    statement = conn.createStatement();
    rs = statement.executeQuery(sqlCommand);
    ResultSetMetaData metaData = rs.getMetaData();
    while (rs.next()) {
     HashMap row = new HashMap();
     for (int i = 1; i <= metaData.getColumnCount(); i++) {
      row.put(metaData.getColumnName(i), rs.getObject(i));
     }
     dataList.add(row);
    }
   } catch (Exception e) {
    dataList.clear();
    throw e;
   } finally {
    if (rs != null) {
     rs.close();
     rs = null;
    }
    if (statement != null) {
     statement.close();
     statement = null;
    }
    if (conn != null) {
     conn.close();
     conn = null;
    }
   }
  }

  return dataList;
 }

 

 

示例二

public synchronized List<HashMap<String, Object>> findList(
   String sqlString, Connection connection) throws Exception {
  if (sqlString == null || connection == null) {
   throw new Exception();
  }
  // System.out.println(sqlString);
  resultList = new ArrayList<HashMap<String, Object>>();
  Statement sta = null;
  try {
   sta = connection.createStatement();
   ResultSet result = sta.executeQuery(sqlString);
   int columnCount = result.getMetaData().getColumnCount();
   while (result.next()) {
    resultMap = new HashMap<String, Object>(columnCount);
    for (int i = 1; i < columnCount + 1; i++) {
     String colName = result.getMetaData().getColumnName(i);
     resultMap.put(colName, result.getObject(colName));
    }
    resultList.add(resultMap);
   }
   return resultList;
  } catch (Exception e) {
   System.out.println(e);
   throw e;
  } finally {
   if (sta != null) {
    sta.close();
   }
  }
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值