1. Determine whether a database table exists:
Obtain the database connection conn, call DatabaseMetaData dbmd = conn. getDataMeta (), and then call the following method:
Copy codeThe Code is as follows:
/**
* Determines whether a database table exists based on the table name.
* @ Param tableName
* @ Return true: The table exists; false: The table does not exist.
*/
Public boolean hasTable (String tableName ){
Init ();
Boolean result = false; // determines whether a table exists.
Try {
ResultSet set = dbmd. getTables (null, null, tableName, null); // obtain the search result
While (set. next () {// if the search result is not empty, the table exists.
Result = true; // set the returned result to true.
}
} Catch (Exception e ){
E. printStackTrace ();
}
Return result;
}
2. Modify the table name:
First, you still need to get the database connection conn, the database description object dbmd, and the Statement object st, and then call the following method:
Copy codeThe Code is as follows:
/**
* Modify the table name
* @ Param srcTableName: name of the source table
* @ Param newTableName new table name
* @ Return true: The table name is successfully modified. false: An error occurred while modifying the table name.
*/
Public boolean renameTable (String srcTableName, String newTableName ){
Init ();
Boolean result = false;
StringBuffer SQL = new StringBuffer ();
Try {
String dataBaseType = dbmd. getDatabaseProductName (); // obtain the Database Type
If ("Microsoft SQL Server"). equals (dataBaseType) {// sqlServer
Try {
SQL. append ("EXEC sp_rename" + "" + srcTableName). append (","). append (newTableName );
Int temp = 0;
Temp = st.exe cuteUpdate (SQL. toString (); // execute the update operation and return the result
If (1 = temp ){
Result = true; // set the return value to true.
}
} Catch (Exception e ){
E. printStackTrace ();
}
} Else if ("HSQL Database Engine"). equals (dataBaseType) | ("MySQL"). equals (dataBaseType) {// hsql and mysql
Try {
SQL. append ("ALTER TABLE" + "" + srcTableName + "" + "RENAME TO" + "" + newTableName );
Int temp = 1;
Temp = st.exe cuteUpdate (SQL. toString (); // execute the update operation and return the result
If (0 = temp ){
Result = true; // set the return value to true.
}
} Catch (Exception e ){
E. printStackTrace ();
}
} Else {// oracle and db2 judgment has not been implemented
}
} Catch (Exception e ){
E. printStackTrace ();
}
// System. out. println (result );
Return result;
}