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 ?
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.
ResultSetMetaData meta = rowSet. getMetaData(); Get the number of columns in the RowSet using the getColumnCount() method.
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.
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
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With