我写了这个Java类来打印DB2数据库的所有表,但问题是:它不打印所有列(我在代码中写了一些提示)。并且每次都打印以前的值!
public class automateExport {
static String value;
public static void main(String[] args) throws SQLException, ClassNotFoundException {
String table_name;
String column_name;
String tableName = null;
String columnType;
int precision;
StringBuilder sb = new StringBuilder(1024);
Connection DB2 = getConnection();
String sql = "SELECT TABSCHEMA,TABNAME,COLNAME,TYPENAME,LENGTH FROM SYSCAT.COLUMNS WHERE TABSCHEMA NOT LIKE 'SYS%' ";
PreparedStatement mainStmt = DB2.prepareStatement(sql);
ResultSet rs = mainStmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
sb.append("create table").append(" ");
rs.next();// if I Comment this line it does not work correctly.but this does not contain one column of table
table_name = rs.getString(2);
sb.append(table_name).append("(");
String str1 = "ADMIN2";
while (rs.next()) {
table_name = rs.getString(2);
if (table_name.equalsIgnoreCase(str1)) {
column_name = rs.getString(3);
columnType = rs.getString(4);
sb.append(" ").append(column_name).append(" ").append(columnType);
precision = rs.getInt(5);
if (precision != 0) {
sb.append("( ").append(precision).append(" )");
sb.append(", ");
}
} else {
sb.append(" ) ").append(";");
System.out.println(sb.toString());
str1 = str1.replaceAll(str1, table_name);
sb.append("create table").append(" ");
sb.append(table_name).append("(");
//rs.previous();
}
// sb.append(" ) ").append(";");
//System.out.println(sb.toString());
}
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection codal = DriverManager.getConnection("jdbc:oracle:thin:@192.168.01.53:1521:orcl", "NAVID",
"oracle");
/* String sql2 = sb.toString();
PreparedStatement m = DB2.prepareStatement(sql2);
m.executeQuery();*/
}
private static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("COM.ibm.db2os390.sqlj.jdbc.DB2SQLJDriver");
Connection connection
= DriverManager.getConnection("jdbc:db2://localhost:50000/navid", "navid", "oracle");
return connection;
}
}
输出是这样的:
run:
create table ADMIN2( NAME VARCHAR( 30 ), ROLE VARCHAR( 50 ), ) ;
create table ADMIN2( NAME VARCHAR( 30 ), ROLE VARCHAR( 50 ), ) ;create table DOCUMENT( ID DECIMAL( 10 ), NAME VARCHAR( 50 ), ) ;
BUILD SUCCESSFUL (total time: 1 second)
答案 0 :(得分:0)
您必须在while循环中初始化StringBuilder:
...
while (rs.next()) {
StringBuilder sb = new StringBuilder(1024);
...
答案 1 :(得分:0)
您可以尝试使用此代码,认为它可能有所帮助。 因为在大多数情况下rs.next在没有while循环的情况下不起作用
sb.append("create table").append(" ");
while(rs.next())
{
table_name = rs.getString(2);
sb.append(table_name).append("(");
}