此程序都是企业级
的数据库开发程序
全面揭示了JAVA对数据库的操作
源代码在线查看: gensql.java
package metadata;
import java.util.*;
import java.sql.*;
import connections.*;
public class GenSql {
public static void main(String args[]) {
Connection conn = null;
try {
conn = ConnectionFactory.getConnection();
DatabaseMetaData dbmd = conn.getMetaData();
String[] tableTypes = new String[] {
"TABLE"
};
ResultSet tables = dbmd.getTables(null, "APP", null, tableTypes);
Vector vtables = new Vector();
String aTable;
// build up a list of tables
while (tables.next()) {
aTable = tables.getString("TABLE_NAME");
vtables.add(aTable);
}
ConnectionFactory.close(tables);
Iterator iterator = vtables.iterator();
// for each table in the list...
String separator;
while (iterator.hasNext()) {
aTable = (String) iterator.next();
// print the create table...
System.out.print("create table " + aTable + " (");
// print the columns
ResultSet columns = dbmd.getColumns(null, null, aTable, null);
separator = "";
while (columns.next()) {
String aColumn;
System.out.print(separator);
System.out.print(columns.getString("COLUMN_NAME"));
int dataType = columns.getInt("DATA_TYPE");
System.out.print(" " + columns.getString("TYPE_NAME"));
if (dataType == java.sql.Types.CHAR
|| dataType == java.sql.Types.VARCHAR) {
System.out.print("(" + columns.getString("COLUMN_SIZE") + ")");
}
String isNullable = columns.getString("IS_NULLABLE");
if (isNullable.equalsIgnoreCase("no")) {
System.out.print(" NOT NULL");
}
separator = ", ";
}
// print the primary keys
ResultSet pkeys = dbmd.getPrimaryKeys(null, null, aTable);
String pkInfo = ", primary key(";
separator = "";
int pkCount = 0;
while (pkeys.next()) {
pkInfo = pkInfo.concat(separator
+ pkeys.getString("COLUMN_NAME"));
separator = ", ";
pkCount++;
}
pkInfo = pkInfo.concat(")");
// if there were primary keys defined, add the pk statement
if (pkCount > 0) {
System.out.print(pkInfo);
}
System.out.println(")\n");
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
ConnectionFactory.close(conn);
}
}
}