Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC/Java - How to check if a table and also a column exist in a database?

Tags:

java

mysql

jdbc

I am using MySql, jdbc and java for my code. I want the code to check if:

1- A table exists in a particular database. 2- A column exists in a particular table of a particular database.

Can you tell me how to do this ?

like image 227
sweet dreams Avatar asked Jul 30 '12 21:07

sweet dreams


People also ask

How do you check if data already exists in database in Java?

We can check if database exists using java. sql. DatabaseMetaData interface. using DatabaseMetaData interface we can obtain the meta data about the database catalog, for example we can obtain the database name, tables available in that database, columns in that table etc.

How do you know if a ResultSet has a column?

ResultSetMetaData meta = rowSet. getMetaData(); Get the number of columns in the RowSet using the getColumnCount() method.

How can you retrieve a list of all tables in a database from JDBC in Java?

You can get the list of tables in the current database in MySQL using the SHOW TABLES query. Show tables; Following JDBC program retrieves the list of tables in the database by executing the show tables query.


2 Answers

A correct way is to use JDBC MetaData

Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
DatabaseMetaData metadata = connection.getMetaData();
ResultSet resultSet;
resultSet = metadata.getTables(null, null, "tablename", null);
if(resultSet.next())
    // Table exists

resultSet = metadata.getColumns(null, null, "tablename", "columnName");
if(resultSet.next())
    // Column exists

To debug your code it might be a good idea to try to fetch all table names first and print them out like this:

resultSet = metadata.getTables(null, null, "%", null);
while(resultSet.next())
    System.out.println(resultSet.getString("TABLE_NAME"));

NB! If no tables are listed, you are using an older version of MySQL JDBC driver with the following bug http://bugs.mysql.com/bug.php?id=20913 you should either upgrade or use database name as the first argument to getTables

like image 147
anttix Avatar answered Nov 14 '22 21:11

anttix


Look for the table:

SELECT COUNT(*)
FROM information_schema.tables 
WHERE table_schema = 'db_name' 
AND table_name = 'table_name';

and if it exists then look for the column:

SELECT * 
FROM information_schema.COLUMNS 
WHERE 
    TABLE_SCHEMA = 'db_name' 
AND TABLE_NAME = 'table_name' 
AND COLUMN_NAME = 'column_name'
like image 33
Samson Avatar answered Nov 14 '22 21:11

Samson