日期:2014-05-16  浏览次数:20550 次

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();
???}
??}
?}