How can I detect if a certain table exists in a given SQL database in Java?
-
1Depends on what database server. There is usually a table with all the table names in it, you could just query it.GEOCHET– GEOCHET2009-05-29 19:53:36 +00:00Commented May 29, 2009 at 19:53
-
sorry this is my first time using SQL, the DB is in AccessBobby– Bobby2009-05-29 19:59:24 +00:00Commented May 29, 2009 at 19:59
-
3java.sql.DatabaseMetaData.getTables is cross-database(JDBC Driver takes care of database differences).adrian.tarau– adrian.tarau2009-05-29 20:00:38 +00:00Commented May 29, 2009 at 20:00
11 Answers
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));
}
1 Comment
Use java.sql.DatabaseMetaData.getTables(null, null, YOUR_TABLE, null). If the table exists, you will get a ResultSet with one record.
Comments
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
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
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
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
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 ......:)🙌