日期:2014-05-16 浏览次数:20411 次
From:http://blog.csdn.net/joeyshi/article/details/4138466
做制作开发平台时,首要的一点是如何取得数据库表结构信息。一般通用的做法就是通过JDBC中的ResultSetMetaData类来进行操作,当你取得了数据库表结构信息后,比如说表的每个字段名称,字段类型等。
首先取得数据库连接后取得DatabaseMetaData。
DatabaseMetaData dbmd = con.getMetaData();
con是一个数据库连接,直接通过连接信息取得。
然后我们就可以取当前数据库中的所有表:
??????? ArrayList v = new ArrayList();
??????? ResultSet rs = null;
??????? String[] typeList = new String[] { "TABLE" };
??????? rs = dbmd.getTables(catalog, schema, null, typeList);
??????? for (boolean more = rs.next(); more; more = rs.next()) {
??????????? String s = rs.getString("TABLE_NAME");
??????????? String type = rs.getString("TABLE_TYPE");
??????????? if (type.equalsIgnoreCase("table") && s.indexOf("$") == -1)
??????????????? v.add(s);
??????? }
其中的rs.getString("TABLE_NAME");方法就是取得表名。
取得表名我们在执行select * from tablename 的方法,取得结果集:
String sql = "select * from "+tableName;
???Statement state = con.createStatement();
???ResultSet rs = state.executeQuery(sql);
???ResultSetMetaData rsmd = rs.getMetaData() ;
???for(int i = 1; i <= rsmd.getColumnCount(); i++)
???{
??????? String colname = rsmd.getColumnName(i);
???????????? String typeName = rsmd.getColumnTypeName(i);
???????????? int itype = rsmd.getColumnType(i);
???????????? int size = rsmd.getColumnDisplaySize(i);
???????????? int precision=rsmd.getPrecision(i);
???????????? int n = rsmd.isNullable(i);
???????????? int scale=rsmd.getScale(i);
???????????? boolean nullable = true;
???????????? switch (n) {
???????????? case 0: // '/0'
???????????????? nullable = false;
???????????????? break;
???????????? case 1: // '/001'
???????????????? nullable = true;
???????????????? break;
???????????? default:
???????????????? nullable = true;
???????????????? break;
???????????? }
???????????? SQLColumn col = new SQLColumn(colname);
???????????? SQLType type = simpleType(typeName, itype);
???????????? if (type.allowsParameters())
???????????????? type.setParameterString("" + size);
???????????? col.setType(type);
???????????? col.setIType(itype);
???????????? col.setSize(size);
???????????? col.setScale(scale);
???????????? col.setPrecision(precision);
???????????? col.setNullable(nullable);
???????????? col.setReadOnly(rsmd.isReadOnly(i));
???????????? col.setAutoIncrement(rsmd.isAutoIncrement(i));
???????????? col.setSearchable(rsmd.isSearchable(i));
???????????? col.setCurrency(rsmd.isCurrency(i));
???????????? col.setCaseSensitive(rsmd.isCaseSensitive(i));
???????????? col.setSigned(rsmd.isSigned(i));
???????????? col.setClassType(rsmd.getColumnClassName(i));
???????????? col.setDisName(rsmd.getColumnLabel(i));
???????????? if ( col.getDisName().length() > 0 )
???????????? ?col.setName(col.getDisName()) ;
????columns.add(col);
?? }
以上操作就取得了表的每个字段信息。得到这些字段信息,就可以为数据库层的各种操作生成所需的代码了。