如何才能利用JDBC代码建立一个与数据库结构无关的JDBC连接呢?
我们可以通过使用RESULTSETMETADATA()方法获得表结构。然后使用OBJECT[]数组遍历结果集。当我们要取得相应的结果时,我们可以使用ITERATOR迭代器。只需遍历迭代器就可以取出结果。
下面的JDBC代码是我写的一个方法:
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.ORACLE(大型网站数据库平台)DRIVER");
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}
【编辑推荐】