private DatabaseHandler() {
createConnection();
COUNTRYNAME();
STATETBL();
}
void createConnection() {
try {
Class.forName("org.postgresql.Driver").newInstance();
conn = DriverManager.getConnection(DB_URL,"postgres", "root");
} catch (Exception e) {
e.printStackTrace();
}
}
国家/地区表
void COUNTRYNAME() {
String TABLE_NAME = "COUNTRY_TBL";
try {
stmt = conn.createStatement();
DatabaseMetaData dbm = conn.getMetaData();
ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null);
if (tables.next()) {
System.out.println("Table " + TABLE_NAME + "already exists. Ready for go!");
} else {
stmt.execute("CREATE TABLE " + TABLE_NAME + "(id SERIAL PRIMARY KEY,\n"
+ " COUNTRYname varchar(20),\n"
+ " COUNTRY2CHAR varchar(50),\n"
+ " DESCR varchar(50),\n"
+ " DESCRSHORT varchar(50)"+")");
}
} catch (SQLException e) {
System.err.println(e.getMessage() + " --- setupDatabase");
} finally {
}
}
州表
void STATETBL() {
String TABLE_NAME = "STATE_TBL";
try {
stmt = conn.createStatement();
DatabaseMetaData dbm = conn.getMetaData();
ResultSet tables = dbm.getTables(null, null, TABLE_NAME.toUpperCase(), null);
if (tables.next()) {
System.out.println("Table " + TABLE_NAME + "already exists. Ready for go!");
} else {
stmt.execute("CREATE TABLE " + TABLE_NAME + "("
+ " id SERIAL PRIMARY KEY,\n"
+ " COUNTRYid varchar(20),\n"
+ " STATE varchar(50),\n"
+ " DESCR varchar(50),\n"
+ " DESCRSHORT varchar(50),\n"
+ " NUMERIC_CD varchar(50),\n"
+ " FOREIGN KEY (COUNTRYid) REFERENCES COUNTRY_TBL(id)"+")");
}
} catch (SQLException e) {
System.err.println(e.getMessage() + " --- setupDatabase");
} finally {
}
}
当我执行上面的代码时,CountryName表在我的数据库中生成,但我的State表没有生成