itkui

年少为何不轻狂!

JDBC之代码复用

在使用JDBC连接数据库的时,我们会采用executeQuery(String sql)获得一个结果集。当数据库结构变化或者获得其他数据库表结果集的时候我们需要将ResultSet结果集根据不同的数据结构重新遍历。
如何才能建立一个与数据库结构无关的JDBC连接呢?我们可以通过使用ResultSetMetaData()方法获得表结构。然后使用Object[]数组遍历结果集。当我们要取得相应的结果时,我们可以使用Iterator迭代器。只要遍历迭代器就可以取出结果。
下面是我写的一个方法:
  1import java.math.BigDecimal;
  2import java.sql.Connection;
  3import java.sql.DriverManager;
  4import java.sql.ResultSet;
  5import java.sql.ResultSetMetaData;
  6import java.sql.SQLException;
  7import java.sql.Statement;
  8import java.util.ArrayList;
  9import java.util.Iterator;
 10import java.util.List;
 11
 12public class newJdbc {
 13    private String url = "jdbc:oracle:thin:@localhost:1521:nitpro";
 14
 15    private String dbUserName = "scott";
 16
 17    private String dbUserPassword = "tiger";
 18
 19    private Connection conn = null;
 20
 21    private Statement stmt = null;
 22
 23    private ResultSet rs = null;
 24
 25    public newJdbc() {
 26        try {
 27            Class.forName("oracle.jdbc.driver.OracleDriver");
 28        }
 catch (ClassNotFoundException e) {
 29            e.printStackTrace();
 30        }

 31    }

 32
 33    public Connection getConnection() {
 34        try {
 35            conn = DriverManager.getConnection(url, dbUserName, dbUserPassword);
 36        }
 catch (SQLException e) {
 37            e.printStackTrace();
 38        }

 39        return conn;
 40    }

 41
 42    public void close(ResultSet rs, Statement stmt, Connection conn) {
 43        if (rs != null{
 44            try {
 45                rs.close();
 46            }
 catch (SQLException e) {
 47                e.printStackTrace();
 48            }

 49        }

 50        if (stmt != null{
 51            try {
 52                stmt.close();
 53            }
 catch (SQLException e) {
 54                e.printStackTrace();
 55            }

 56        }

 57        if (conn != null{
 58            try {
 59                conn.close();
 60            }
 catch (SQLException e) {
 61                e.printStackTrace();
 62            }

 63        }

 64    }

 65
 66    public List query(String sql) {
 67        List list = new ArrayList();
 68
 69        conn = this.getConnection();
 70        try {
 71            stmt = conn.createStatement();
 72            rs = stmt.executeQuery(sql);
 73            //获取数据库表结构
 74            ResultSetMetaData rsm = rs.getMetaData();
 75            //取得数据库的列数
 76            int col = rsm.getColumnCount();
 77            //生成col长度的Object数组
 78            Object[] obj = new Object[col];
 79            //遍历结果集,将结果存入Object数组
 80            while (rs.next()) {
 81                for (int i = 0; i < col; i++{
 82                    obj[i] = rs.getObject(i + 1);
 83                }

 84                list.add(obj);
 85            }

 86        }
 catch (SQLException e) {
 87            e.printStackTrace();
 88        }
 finally {
 89            this.close(rs, stmt, conn);
 90        }

 91        return list;
 92    }

 93
 94    public void update(String sql) {
 95        try {
 96            conn = this.getConnection();
 97            stmt = conn.createStatement();
 98            stmt.executeUpdate(sql);
 99        }
 catch (SQLException e) {
100            e.printStackTrace();
101        }

102    }

103
104    public static void main(String args[]) {
105        newJdbc nj = new newJdbc();
106        String sql = "select * from users";
107        List list = nj.query(sql);
108        //返回list的迭代器
109        Iterator it = list.iterator();
110        //遍历迭代器,取出结果
111        while (it.hasNext()) {
112            Object[] o = (Object[]) it.next();
113            int id = ((BigDecimal) o[0]).intValue();
114            System.out.println(id);
115        }

116
117    }

118}

119

posted on 2007-06-09 14:17 itkui 阅读(1459) 评论(13)  编辑  收藏 所属分类: Java

评论

# re: JDBC之代码复用 2007-06-09 17:28 search-computer

刚写过一个类似的,呵呵  回复  更多评论   

# re: JDBC之代码复用 2007-06-09 17:43 itkui

@search-computer
那你考虑的满周到的呀!
  回复  更多评论   

# re: JDBC之代码复用 [未登录] 2007-06-09 18:48 RoBeRt

why not use spring jdbc template  回复  更多评论   

# re: JDBC之代码复用 2007-06-09 19:05 itkui

@RoBeRt
spring没学过。现在还在学习阶段。
Java框架无不是让代码复用。  回复  更多评论   

# re: JDBC之代码复用 [未登录] 2007-06-09 21:07 RoBeRt

Too many try catch block make people weary
We use frameworks not only for they're popular but also to reduce redundancy.
Frankly speaking yours codes just like a toy.The JDK 6.0 has released a new way to connect the database.You should see it in the document   回复  更多评论   

# re: JDBC之代码复用 2007-06-09 21:21 itkui

@RoBeRt
谢谢提醒,找个时间好好研究下!
这个代码没有太大的实际意义,
真正开发的时候会用hibernate。。。  回复  更多评论   

# re: JDBC之代码复用 [未登录] 2007-06-10 09:49 xmlspy

使用spring jdbcTemplate 什么问题都解决了

从性能和复用性上都比较平均

是个不错的选择  回复  更多评论   

# re: JDBC之代码复用 2007-06-10 14:01 阿南

对,还有对事务的支持,非常简单~  回复  更多评论   

# re: JDBC之代码复用 2007-06-10 23:01 b_will

78 Object[] obj = new Object[col];
79 //遍历结果集,将结果存入Object数组
80 while (rs.next()) {
81 for (int i = 0; i < col; i++) {
82 obj[i] = rs.getObject(i + 1);
83 }
84 list.add(obj);
85 }

好像不对呀,最后的结果是list中的所有数据都一样。
Object[] obj = new Object[col]; 应该放在while 循环里。
  回复  更多评论   

# re: JDBC之代码复用 2007-06-10 23:14 itkui

@b_will
没错的,obj[i]是在for循环里面的,这样就可以将结果集全部存入
obj数组中!
不经过验证我是不会帖出来的!
不过,谢谢你的留意!  回复  更多评论   

# re: JDBC之代码复用 [未登录] 2007-06-13 09:14 tony

特别好,有用!  回复  更多评论   

# re: JDBC之代码复用 2007-06-19 09:31 轩朗=maninred

关于数据库的配置可以抽取到properties文件中,还有关于在结果集中将结果放至一个数字中的方法不是很好,这样就却少了类型检查,在拿出结果后直接进行VO的装配比较好。

jdbc这类代码本来要的就是灵活,效率和细粒度控制,所以免不了代码的复杂性会很高,其实用Spring的jdbcTemplate代码也不会少很多。在实际开发中要么用ORM框架,要么就用jdbc直接写出dao。  回复  更多评论   

# re: JDBC之代码复用 2007-07-12 16:20 Scott.Pan

不错,让我了解JDBC又多了些。理解了内部机制,写的东西都明了些。  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

留言簿(1)

随笔档案(24)

收藏夹(15)

好站珍藏

学习资源

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜