Step By Step(Java JDBC篇) (五)

2014-11-24 03:19:38 · 作者: · 浏览: 3
8 } catch (SQLException e) {

69 e.printStackTrace();

70 }

71 }

72 }

73 }

4. 通过结果集的方式获取Columns的Metadata信息。

1 public class MyTest {

2 private static Connection getConnection() throws SQLException,

3 ClassNotFoundException {

4 Class.forName("oracle.jdbc.driver.OracleDriver");

5 Properties conProps = new Properties();

6 conProps.put("user", "sys");

7 conProps.put("password", "helloworld");

8 conProps.put("internal_logon", "sysdba");

9 return DriverManager.getConnection(

10 "jdbc:oracle:thin:@//192.168.1.101:1526/OraHome", conProps);

11 }

12 private static void getColumnNames(ResultSet rs) throws SQLException {

13 ResultSetMetaData rsMetaData = rs.getMetaData();

14 int numberOfColumns = rsMetaData.getColumnCount();

15 for (int i = 1; i <= numberOfColumns; ++i) {

16 String columnName = rsMetaData.getColumnName(i);

17 System.out.println("column = " + columnName);

18 }

19 }

20 public static void main(String[] args) throws ClassNotFoundException {

21 Connection conn = null;

22 Statement stmt = null;

23 ResultSet rs = null;

24 try {

25 conn = getConnection();

26 String query = "select * from user_tables";

27 stmt = conn.createStatement();

28 rs = stmt.executeQuery(query);

29 getColumnNames(rs);

30 } catch (Exception e) {

31 e.printStackTrace();

32 } finally {

33 // release database resources

34 try {

35 rs.close();

36 stmt.close();

37 conn.close();

38 } catch (SQLException e) {

39 e.printStackTrace();

40 }

41 }

42 }

43 }

5. 通过可滚动结果集逆向访问行记录。

需要注意的是,如果结果集中数据量比较大,而可滚动结果集的底层实现方式是将当前查询的所有记录都传到客户端本地,然后再自行维护结果集的游标信息。因为在原生的数据库C接口API中,如Oracle的OCI和MySQL的API中,均不支持此种方式的结果集,而且结果集中的数据也是分批批量下载到本地的,而这种可滚动结果集的实现则是完全交由上层来完成的。

1 public class MyTest {

2 private static Connection getConnection() throws SQLException,

3 ClassNotFoundException {

4 Class.forName("oracle.jdbc.driver.OracleDriver");

5 Properties conProps = new Properties();

6 conProps.put("user", "sys");

7 conProps.put("password", "helloworld");

8 conProps.put("internal_logon", "sysdba");

9 return DriverManager.getConnection(

10 "jdbc:oracle:thin:@//192.168.1.101:1526/OraHome", conProps);

11 }

12

13 public static void main(String[] args) throws ClassNotFoundException {

14 Connection conn = null;

15 Statement stmt = null;

16 ResultSet rs = null;

17 try {

18 conn = getConnection();

19 stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,

20