开发者

How to check whether table with given name exists in oracle through Java?

I have csv file and i want to import that data t开发者_StackOverflow中文版o oracle database. but before that i want it to check whether table 'xyz' exist in database or not.

I want to do it through java .. anyone knows how to do it through java ?


You can use the available meta data:

DatabaseMetaData meta = con.getMetaData();
  ResultSet res = meta.getTables(null, null, null, 
     new String[] {"TABLE"});
  while (res.next()) {
     System.out.println(
        "   "+res.getString("TABLE_CAT") 
       + ", "+res.getString("TABLE_SCHEM")
       + ", "+res.getString("TABLE_NAME")
       + ", "+res.getString("TABLE_TYPE")
       + ", "+res.getString("REMARKS")); 
  }

See here for more details.


Wikipedia has some good info on getting at oracle metadata.

 SELECT
 COUNT(1)
 FROM
 ALL_TABLES
 WHERE
 TABLE_NAME = 'NAME_OF_TABLE'

Replace NAME_OF_TABLE with the name of your table and if you get a result of 1, you have your table.


You can just run a dummy SQL like:

select from * 'xyz' where 1 = 2

If you don't get any Exception like "ORA-00942 Table or View doesnt exist" then the Table exists.

Or you choose the elegant way like:

select * from USER_OBJECTS where OBJECT_TYPE = 'TABLE' and OBJECT_NAME = 'xyz';


public class Main 
{

  public static void main(String[] args) throws Exception 
  {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//server.local:1521/prod", "scott", "tiger");
    conn.setAutoCommit(false);
    DatabaseMetaData dbmd = conn.getMetaData();
    ResultSet rset = dbmd.getTables("", "SCOTT", "EMP", null);
    while (rs.next()) 
    {
      System.out.println(rs.getString(3));
      //OR use whatever progmatically you want to do if table exist
    }  
    stmt.close();
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜