I need to check if a table with a specific "tablename" exists in a database from my java program.
The database may be of different type, viz. MS SQL Server, Oracle, DB2. I have a connection object to the database. Is there a single method that can work for all the types of databases? I might have to extend the java program to support more db Types, thus a single approach for all DB types would be very much helpful.
The code that I am using. This appears to work correctly against a SQL Server database but does not find the table in Oracle or DB2
DatabaseMetaData meta = conn.getMetaData();
ResultSet res = meta.getTables(null, null, "TABLE_NAME", null);
if(!res.next()){
//table does not exist.
} else{
//table exists.
}
You can use the DatabaseMetaData.getTables() procedure to search the database for tables with a particular pattern. If you search for an exact name, you'll either get an empty ResultSet
or a ResultSet
with a single row telling you that the table exists.
This works for me against an Oracle database whether the table is owned by the current user or a different user.
import java.sql.*;
import oracle.jdbc.*;
public class TableExists
{
public static String exists(String tableName)
throws SQLException
{
Connection conn = new OracleDriver().defaultConnection();
DatabaseMetaData meta = conn.getMetaData();
ResultSet res = meta.getTables(null, null, tableName, null);
if(!res.next()){
return "Nope";
} else{
return "Yup";
}
}
}
您可以尝试DatabaseMetaData
getTables()
方法。
Very simplistic:
SELECT
1
FROM
TABLE
;
If it throws an exception the table does not exist (or something else is wrong). Otherwise:
http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html#getTables(java.lang.String , java.lang.String, java.lang.String, java.lang.String[])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.