Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if table exists [duplicate]

Tags:

java

jdbc

I have a desktop application with a database embedded in it. When I execute my program I need to check that specific table exists, or create it if not.

Given a Connection object named conn for my database, how could I check this?

like image 709
Dmitry Avatar asked May 31 '10 10:05

Dmitry


People also ask

How do I filter duplicates in SQL?

The go to solution for removing duplicate rows from your result sets is to include the distinct keyword in your select statement. It tells the query engine to remove duplicates to produce a result set in which every row is unique.

How do I find duplicate rows in two tables in SQL?

Check for Duplicates in Multiple Tables With INNER JOINUse the INNER JOIN function to find duplicates that exist in multiple tables. Sample syntax for an INNER JOIN function looks like this: SELECT column_name FROM table1 INNER JOIN table2 ON table1. column_name = table2.


2 Answers

DatabaseMetaData dbm = con.getMetaData(); // check if "employee" table is there ResultSet tables = dbm.getTables(null, null, "employee", null); if (tables.next()) {   // Table exists } else {   // Table does not exist } 
like image 158
RealHowTo Avatar answered Oct 16 '22 00:10

RealHowTo


You can use the available meta data:

  DatabaseMetaData meta = con.getMetaData();   ResultSet res = meta.getTables(null, null, "My_Table_Name",       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. Note also the caveats in the JavaDoc.

like image 37
Brian Agnew Avatar answered Oct 16 '22 02:10

Brian Agnew