38

How can I detect if a certain table exists in a given SQL database in Java?

3
  • 1
    Depends on what database server. There is usually a table with all the table names in it, you could just query it. Commented May 29, 2009 at 19:53
  • sorry this is my first time using SQL, the DB is in Access Commented May 29, 2009 at 19:59
  • 3
    java.sql.DatabaseMetaData.getTables is cross-database(JDBC Driver takes care of database differences). Commented May 29, 2009 at 20:00

11 Answers 11

43

You can use DatabaseMetaData.getTables() to get information about existing tables.

This method works transparently and is independent of the database engine. I think it queries information schema tables behind the scenes.

Edit:

Here is an example that prints all existing table names.

DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
  System.out.println(rs.getString(3));
}
Sign up to request clarification or add additional context in comments.

1 Comment

That example does not work for me. Please see - stackoverflow.com/questions/11699023/…
14

Use java.sql.DatabaseMetaData.getTables(null, null, YOUR_TABLE, null). If the table exists, you will get a ResultSet with one record.

See DatabaseMetaData.getTables

Comments

2

For ALL ANSI-compliant databases: (mySQL, SQL Server 2005/2008, Oracle, PostgreSQL, SQLLite, maybe others)

select 1 from information_schema.tables where table_name = @tableName

Comments

1

This is not a language-specific, but a database-specific problem. You'd query the metadata in the database for the existence of that particular object.

In SQL Server for instance:

SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[table]')
   AND type in (N'U')

Comments

1

Write a query that queries the table/view that will list the tables (this is different depending on DB vendor). Call that from Java.

Googling information_schema.tables will help a lot.

1 Comment

Usually using DatabaseMetaData is better, as it is DB-independent.
1

Depending on the DB, you can do (MySQL)

SHOW TABLES

or (Oracle)

SELECT * FROM user_objects WHERE object_type = 'TABLE'

or another thing for SQL Server. Cycle through the results for MySQL or further filter on the Oracle one.

1 Comment

Good answer, it's very convenient
1

Why not just see if it is in sysobjects (for SQL Server)?

SELECT [name] FROM [sysobjects] WHERE type = 'U' AND [name] = 'TableName'

Comments

1

There is a JDBC feature, database vendor independent - see [java.sql.DatabaseMetaData#getTables()][1]

You can get the DatabaseMetaData instance by calling java.sql.Connection#getMetaData()

[1]: http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html#getTables(java.lang.String, java.lang.String, java.lang.String, java.lang.String[])

Comments

1

This is what worked for me for jdbc:derby:

//Create Staff table if it does not exist yet
String tableName = "STAFF";
boolean exists = conn.getMetaData().getTables(null, null, tableName, null).next();
if(!exists){
    s = conn.createStatement();
    s.execute("create table staff(lastname varchar(30), firstname varchar(30), position varchar(20),salary double,age int)");
    System.out.println("Created table " + tableName);
}

Note that tableName has to be all caps.

Comments

1

There are two options available to check that a table does or doesn't exist in a particular database


First using DatabaseMetaData

import java.sql.*;
import java.util.*;
import java.io.*;

public class checktableexistusingdatabasemetadata {
    public static void main(String[] args) {
        try {
            // load the driver class
            Class.forName("com.mysql.cj.jdbc.Driver");
            // make connection we pass these threee things for connection our program to the
            // database >> url,username, password
            Connection todb = DriverManager.getConnection("jdbc:mysql://localhost:portnumberTCP/databasename", "username",
                    "password");       
            DatabaseMetaData dbm = todb.getMetaData();
            // check if "newdata" table is there
            ResultSet tables = dbm.getTables(null, null, "newdataindbf", null);
            if (tables.next()) {
                System.out.println("The table you are trying to create that already exists in the database so try a ne name bcz same name table cannot exixts in the particular database .....:)");
            } else {
                System.out.println("Your query will be executed .....:)");
                // query for creating a table into the database
                String qry = "create table newdataindbf(nid int(29) primary key auto_increment,nname varchar(200) not null,ncity varchar(299))";
                // statement is a interface here we are using it to create a table
                Statement stmt = todb.createStatement();
                // here we are passing the query so that it is executed
                stmt.executeUpdate(qry);
                // if here the execute query works then this message will be printed or else we
                // will get an exception
                System.out.println("Table is created succesfully ....:)");
                // close connection
                todb.close();
            }
        }
        catch(Exception e){
            System.out.println("Something went wrong >> "+e.getMessage());
        }
    }
}

Output :-

output when table doesn't exists inside the database ..>
Your query will be executed .....:)
Table is created succesfully ....:)

output when the table already exists inside the database ..> 
The table you are trying to create that already exists in the database so try a ne name bcz same name table cannot exixts in the particular database .....:)

Second by using the query >> information_schema

import java.sql.*;
import java.util.*;
import java.io.*;

public class checktableusinginformatioinschema {
    public static void main(String[] args) {
        try {
            // load the driver class
            Class.forName("com.mysql.cj.jdbc.Driver");
            // make connection we pass these threee things for connection our program to the
            // database >> url,username, password
            Connection todb = DriverManager.getConnection("jdbc:mysql://localhost:portnumberTCP/databasename", "username",
                    "password");
            PreparedStatement preparedStatement = todb.prepareStatement(
                    "SELECT count(*) FROM information_schema.tables WHERE table_name = 'newdataindbd' LIMIT 1");
            ResultSet resultSet = preparedStatement.executeQuery();
            resultSet.next();
            // returns true--> 0 or false--> 1 but here it returns true or false ...:)
            // System.out.println(resultSet.getInt(1)!=0);
            if (resultSet.getInt(1) != 0 == true) {
                System.out.println(
                        "The table you are trying to create with the name already exists in the database try to create the table with some different name bcz same name table cannot exists in a particular database ......:) ");
            } else {
                System.out.println("Your query will be executed .....:)");
                // query for creating a table into the database
                String qry = "create table newdataindbd(nid int(29) primary key auto_increment,nname varchar(200) not null,ncity varchar(299))";
                // statement is a interface here we are using it to create a table
                Statement stmt = todb.createStatement();
                // here we are passing the query so that it is executed
                stmt.executeUpdate(qry);
                // if here the execute query works then this message will be printed or else we
                // will get an exception
                System.out.println("Table is created succesfully ....:)");
                // close connection
                todb.close();
            }

        } catch (Exception e) {
            System.out.println("Something went wrong ........ ");
        }
    }
}

Output >>

output when the table doesn't exists >>
Your query will be executed .....:)
Table is created succesfully ....:)

output when the table exists in the db >>
The table you are trying to create with the name already exists in the
database try to create the table with some different name bcz same name table cannot exists in a particular database ......:)

⛅Hope so this will help😇 out to understand ......:)🙌

Comments

0

For MS Access:

Select Count(*) From MSysObjects 
Where type=1 And name='your_table_name_here'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.