I am trying to make simple java code that will check if a table and/or a column exists in a MySQL DB. Should I use Java code to do the checking or make a SQL query string an
Knowing that you can practically select a column from a table using the following SQL statement (in MySQL):
show columns from TABLE_NAME where field = 'FIELD_NAME';
You could do something like:
...
PreparedStatement preparedStatement =
connection.prepareStatement(
"show columns from [TABLE_NAME] where field = ?");
preparedStatement.setString(1, columName);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
System.out.println("column exists!");
} else {
System.out.println("column doesn't exists!");
}
...
In Apache Derby (SQL)
E.g. check if column exists:
SELECT ss.SCHEMANAME, st.TABLENAME, sc.COLUMNNAME FROM SYS.SYSSCHEMAS ss
INNER JOIN SYS.SYSTABLES st ON st.SCHEMAID = ss.SCHEMAID AND st.TABLENAME = <YOUR TABLE NAME>
INNER JOIN SYS.SYSCOLUMNS sc ON sc.REFERENCEID = st.TABLEID AND sc.COLUMNNAME = <YOUR COLUMN NAME>
WHERE ss.SCHEMANAME = <YOUR SCHEMA>
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='table_schema'
AND TABLE_NAME='table_name'
AND COLUMN_NAME='column_name'
If this sql returns nothing - column not exists. You can execute this query on java side, but this depends what you use (JPA, JDBC, JDBCTemplate).
To check if a table exist you can use DatabaseMetaData in this way :
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getTables(null, null, "table_name", null);
if (rs.next()) {
//Table Exist
}
And to check if a column exist you can use it in a similar way :
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getColumns(null, null, "table_name", "column_name");
if (rs.next()) {
//Column in table exist
}