/** * Add a column to an existing database table, if it does not already exist. * It is the users responsibility to close the connection after use. * @param con A connection to the database. * @param tableName The table to add the database too * @param columnName The column to add * @param type The SQL type to add * @throws SQLException if something goes wrong */ public static void addColumn(Connection con, String tableName, String columnName, Type type) throws SQLException { if (!DatabaseUtil.tableExists(con, tableName)) { throw new IllegalArgumentException("there is no table named " + tableName + " in this" + " database to add a new column to"); } if (DatabaseUtil.columnExists(con, tableName, columnName)) { return; } if (!DatabaseUtil.isLegalColumnName(columnName)) { throw new IllegalArgumentException("This is not a legal column name: " + columnName); } String sql = "ALTER TABLE " + tableName + " ADD COLUMN " + columnName + " " + type.getSQLType(); PreparedStatement stmt = con.prepareStatement(sql); LOG.info(stmt.toString()); stmt.executeUpdate(); }
/** * Add a column to an existing database table, if it does not already exist. * It is the users responsibility to close the connection after use. * @param con A connection to the database. * @param tableName The table to add the database too * @param columnName The column to add * @param type The SQL type to add * @throws SQLException if something goes wrong */ public static void addColumn(Connection con, String tableName, String columnName, Type type) throws SQLException { if (!DatabaseUtil.tableExists(con, tableName)) { throw new IllegalArgumentException("there is no table named " + tableName + " in this" + " database to add a new column to"); } if (DatabaseUtil.columnExists(con, tableName, columnName)) { return; } if (!DatabaseUtil.isLegalColumnName(columnName)) { throw new IllegalArgumentException("This is not a legal column name: " + columnName); } String sql = "ALTER TABLE " + tableName + " ADD COLUMN " + columnName + " " + type.getSQLType(); PreparedStatement stmt = con.prepareStatement(sql); LOG.info(stmt.toString()); stmt.executeUpdate(); }
public void testColumnNameLegality() { assertFalse(DatabaseUtil.isLegalColumnName(null)); assertFalse(DatabaseUtil.isLegalColumnName("")); assertFalse(DatabaseUtil.isLegalColumnName("FOO")); assertFalse(DatabaseUtil.isLegalColumnName("foo!")); assertFalse(DatabaseUtil.isLegalColumnName("foo; drop table userprofile;")); assertTrue(DatabaseUtil.isLegalColumnName("foo")); assertTrue(DatabaseUtil.isLegalColumnName("foo123")); assertTrue(DatabaseUtil.isLegalColumnName("foo_bar")); assertTrue(DatabaseUtil.isLegalColumnName("foo_bar_123")); }