Today, I encountered a problem during the day, which required me to determine whether a known table name exists in the database. This kind of problem is quite frustrating. I first searched on GG and then on Baidu. The methods I found either only apply to specific databases or do not consider the issue of exclusive locks. Fortunately, I thought of SUN's API, which has an interface called DatabaseMetaData under the java.sql package. It's very simple to use this interface to check if the table you want exists in the database. As long as your JDBC driver supports it, it is highly versatile. I wrote some DEMO code for your reference.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
//detect unknown tables by name
// TableName:tablename
public class Main {
public static void main(String[] argv) throws Exception {
Connection c = null; //db connection
DatabaseMetaData dbm = c.getMetaData();
ResultSet rs = dbm.getTables(null, null, "tablename", null);
if (rs.next()) {
System.out.println("Exists");
}
else {
System.out.println("Not Exist");
}
}
}
The following is the function prototype for getTables: public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException
. The corresponding parameter explanations are as follows:
catalog
: It is the name of the directory, generally the name of the database. For example, the database named "test" is "test". If it is null, it will search all tables.schemaPattern
: It is the pattern for matching data tables. If it is null, the schema will not be considered.tableNamePattern
: It is the matching of the data table name. In my example above, I directly used the table name, which can only match one table. Here, you can use regular expressions to match multiple tables.types
: It is an array of data table types, such as the commonly used MyISAM and InnoDB in MySQL. It can search for multiple types of tables.