不是最好的答案,但由于我使用的是 java,我可以尝试 printf 来对齐列的类型:
pwFile.printf("%-45s %s,\n", columnsName.get(i), columnsType.get(i))
此方法在文件中写入表的 DDL,使列小写并对齐它们的类型:
public static void writeTableDDL(String table) throws SQLException {
Connection con = null;
PreparedStatement preparedStatement = null;
String filename = table.toUpperCase()+".sql";
PrintWriter pwFile = null;
ArrayList<String> columnsName = new ArrayList<String>() ;
ArrayList<String> columnsType = new ArrayList<String>() ;
ArrayList<String> columnsNullable = new ArrayList<String>() ;
String selectSQL ="SELECT column_name , DECODE(nullable, 'Y', ' ', 'NOT NULL') nullable , " +
" DECODE(data_type, 'RAW', data_type || '(' || data_length || ')', 'CHAR', data_type || '(' || data_length || ')', 'VARCHAR', data_type || '(' || data_length || ')', 'VARCHAR2', data_type || '(' || data_length || ')', 'NUMBER', NVL2( data_precision, DECODE( data_scale, 0, data_type || '(' || data_precision || ')' , data_type || '(' || data_precision || ',' || data_scale || ')'), data_type), data_type ) data_type "
+ " FROM user_tab_columns WHERE table_name = '"+table+"' ORDER BY column_id";
try
{
con = DBConnection.getConnection();
preparedStatement = con.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
columnsName.add(rs.getString(1));
columnsType.add(rs.getString(3));
columnsNullable.add(rs.getString(2));
}
}catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (con != null) {
con.close();
}
}
try {
pwFile = new PrintWriter(filename);
pwFile.println("CREATE TABLE "+table+"\n(");
for(int i=0; i <= columnsName.size()-1; i++) {
columnsName.set(i, columnsName.get(i).toLowerCase());
}
for(int i=0; i < columnsName.size()-1; i++) {
pwFile.printf("%-45s %s,\n", columnsName.get(i), columnsType.get(i));
}
pwFile.printf("%-45s %s\n", columnsName.get(columnsName.size()-1), columnsType.get(columnsName.size()-1));
pwFile.print(")\nTABLESPACE "+getTablespace(table)+"\n/");
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(SecurityException e) {
e.printStackTrace();
} finally {
if(pwFile != null){
pwFile.close();
}
}
}