Java alter table add

JDBC: Alter Table Example

This tutorial describe how to alter existing table using JDBC API.

This tutorial describe how to alter existing table using JDBC API.

JDBC: Alter Table Example

This tutorial describe how to alter existing table using JDBC API.

Alter Table :

Alter table means editing the existing table. You can add new field, drop unused field and alter properties of field.
We can change the structure of table student in the following ways —

  1. You can add new field —
    sql= » ALTER TABLE student ADD location varchar(30)»
  2. You can delete the unused field-
    sql=»ALTER TABLE student DROP location»
  3. You can replace the existing field name with new name.
    sql=»ALTER TABLE student CHANGE location address varchar(30)»
  4. You can also alter the field definition.
    sql=»ALTER TABLE student ALTER location SET DEFAULT ‘New Delhi’ «
  5. You can alter the field definition by using MODIFY keyword.
    sql=»ALTER TABLE student MODIFY roll_no varchar(20) «

Example : In this example we are adding new field ‘location‘ to the table ‘student’.

package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; class AlterTable < public static void main(String[] args) < System.out.println("Table Alter Example!"); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "students"; String driverName = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "root"; try < // Creating db connection Class.forName(driverName); con = DriverManager.getConnection(url + dbName, userName, password); try < Statement st = con.createStatement(); String sql = "ALTER TABLE student add location varchar(30)"; st.executeUpdate(sql); System.out.println("Table is altered successfully"); >catch (SQLException s) < System.out.println(s); >con.close(); > catch (Exception e) < e.printStackTrace(); >> >
Table Alter Example! Table is altered successfully

Now Your table looks like this —

Читайте также:  Sublime text расширения для html

Источник

Java alter table add

Use ALTER TABLE statements to either add new fields to a table definition, or delete a currently existing field definition. You can also use an ALTER TABLE statement to change the default Time-to-Live (TTL) value for a table, and to add an IDENTITY column to a table.

ALTER TABLE ADD field

To add a field to an existing table, use the ADD statement:

ALTER TABLE table-name (ADD field-definition)

See Field Definitions for a description of what should appear in field-definitions , above. For example:

ALTER TABLE Users (ADD age INTEGER)

You can also add fields to nested records. For example, if you have the following table definition:

CREATE TABLE u (id INTEGER, info record(firstName String)), PRIMARY KEY(id)) 

then you can add a field to the nested record by using dot notation to identify the nested table, like this:

ALTER TABLE u(ADD info.lastName STRING)

ALTER TABLE DROP Option

To delete a field from an existing table, use the DROP option:

ALTER TABLE table-name (DROP field-name)

For example, to drop the age field from the Users table:

ALTER TABLE Users (DROP age)

You cannot drop a field if it is the primary key, or if it participates in an index.

You can also us the ALTER TABLE MODIFY FIELD clause to add, drop, or modify an IDENTITY column in a table.

ALTER TABLE USING TTL

To change the default Time-to-Live (TTL) value for an existing table, use the USING TTL statement:

ALTER TABLE table-name USING TTL ttl
ALTER TABLE Users USING TTL 4 days

In case of MR Tables, you can not use the USING TTL clause along with the IN REGIONS clause. That is, you can not alter an MR table’s TTL value and regions in a single statement.

For more information on the USING TTL statement, see USING TTL.

ALTER TABLE ADD REGIONS

The add regions clause lets you link an existing multi-region table (MR Table) with new regions in a multi-region Oracle NoSQL Database environment.

The add regions clause is used in expanding MR Tables to new regions. See Use Case 2: Expand a Multi-Region Table in the Administrator’s Guide .

ALTER TABLE DROP REGIONS

The drop regions clause lets you disconnect an existing multi-region table (MR Table) from a participating region in a multi-region Oracle NoSQL Database environment.

The drop regions clause is used in contracting MR Tables to fewer regions. See Use Case 3: Contract a Multi-Region Table in the Administrator’s Guide .

Источник

Java alter table add

Use ALTER TABLE statements to either add new fields to a table definition, or delete a currently existing field definition. You can also use an ALTER TABLE statement to change the default Time-to-Live (TTL) value for a table, and to add an IDENTITY column to a table.

ALTER TABLE ADD field

To add a field to an existing table, use the ADD statement:

ALTER TABLE table-name (ADD field-definition)

See Field Definitions for a description of what should appear in field-definitions , above. For example:

ALTER TABLE Users (ADD age INTEGER)

You can also add fields to nested records. For example, if you have the following table definition:

CREATE TABLE u (id INTEGER, info record(firstName String)), PRIMARY KEY(id)) 

then you can add a field to the nested record by using dot notation to identify the nested table, like this:

ALTER TABLE u(ADD info.lastName STRING)

ALTER TABLE DROP Option

To delete a field from an existing table, use the DROP option:

ALTER TABLE table-name (DROP field-name)

For example, to drop the age field from the Users table:

ALTER TABLE Users (DROP age)

You cannot drop a field if it is the primary key, or if it participates in an index.

You can also us the ALTER TABLE MODIFY FIELD clause to add, drop, or modify an IDENTITY column in a table.

ALTER TABLE USING TTL

To change the default Time-to-Live (TTL) value for an existing table, use the USING TTL statement:

ALTER TABLE table-name USING TTL ttl
ALTER TABLE Users USING TTL 4 days

In case of MR Tables, you can not use the USING TTL clause along with the IN REGIONS clause. That is, you can not alter an MR table’s TTL value and regions in a single statement.

For more information on the USING TTL statement, see USING TTL.

ALTER TABLE ADD REGIONS

The add regions clause lets you link an existing multi-region table (MR Table) with new regions in a multi-region Oracle NoSQL Database environment.

The add regions clause is used in expanding MR Tables to new regions. See Use Case 2: Expand a Multi-Region Table in the Administrator’s Guide .

ALTER TABLE DROP REGIONS

The drop regions clause lets you disconnect an existing multi-region table (MR Table) from a participating region in a multi-region Oracle NoSQL Database environment.

The drop regions clause is used in contracting MR Tables to fewer regions. See Use Case 3: Contract a Multi-Region Table in the Administrator’s Guide .

Источник

Изменение структуры таблицы

И наконец самая вкусная часть работы с базами — изменение базы данных. Если ты думаешь, что это что-то очень простое, то вот тебе анекдот в тему:

 Мастер СТО, вытирая руки, сдает клиенту машину и попутно болтает: - А вот вы кем работаете? - Кардиохирургом, операции на сердце провожу. - И много платят? - 20,000$ за операцию. - Нифига себе. А ведь мы, по сути, одним и тем же занимаемся, движки перебираем, а мне всего 300$ платят. - Хочешь так же, как я, заработать? - Хочу. Хирург заводит движок в машине и обращается к мастеру: - Перебирай! 

С базами данных прямо такая же ситуация. Ты хочешь вынести часть данных в отдельную таблицу? Хорошо, тебе нужно:

  • создать новую таблицу
  • скопировать данные в эту новую таблицу
  • удалить колонки из старой таблицы
  • поменять все SQL-запросы, которые ссылались на старую таблица
  • добавить SQL-запросы, которые будут обращаться к новой таблице
  • поменять Java-код, которые работал с таблицами по-старому
  • поменять сценарии бэкапа и восстановления данных, так как теперь структуры таблиц не совпадают
  • если у тебя есть тестовые данные для разработчиков, нужно поменять и их

Хотя в реальности бывает еще хуже:

Новая структура БД:

  • сначала меняешь структуру таблиц на машине разработчика
  • потом убеждаешься, что такая структура действительно лучше
  • утверждаешь новую структуру БД

Скрипты миграции:

  • пишешь скрипты, которые будут менять таблицые данный и т. д. на реальной базе данных
  • запускаешь эти скрипты на машине со старой структурой базы и смотришь, как она меняется
  • верифицируйшь все критические места новой базы

Апдейт на проде

  • останавливаешь production-базу
  • делаешь полный бэкап
  • выполняешь скрипты
  • так как на проде обычно куча, данных скрипты могут работать часами

Запускаешь прод и надеешься, что тебе не придется все откатывать назад.

6.2 Оператор ALTER TABLE

С другой стороны, сам скрипт, который меняет структуру таблиц, очень простой. Чем-то он похож на скрипт создания таблицы. Общий вид запроса на изменения таблицы:

 ALTER TABLE таблица команда 1, команда 2, команда N 

Команды бывают очень разными, но можно выделить три основные группы:

  • ADD — добавляет что-то в таблицу
  • MODIFY — меняет что-то в таблице
  • DROP — удаляет что-то в таблице

И когда я говорю что-то, то речь идет не о данных, а о структуре таблицы.

Например, ты решаешь добавить в таблицу новую колонку, тогда нужно выполнить такой запрос:

 ALTER TABLE таблица ADD COLUMN имя тип 

Давай напишем запрос, который добавит в нашу таблицу employee колонку email:

 ALTER TABLE employee ADD COLUMN email VARCHAR(10) 

Теперь поменяем длину строки email с 10 на 100: для этого нам понадобится новый скрипт:

 ALTER TABLE employee MODIFY COLUMN email VARCHAR(100) 

Если ты хочешь поменять какие-то атрибуты колонки, но не ее тип, то тебе нужна команда ALTER COLUM . Давай установим значение email по умолчанию:

 ALTER TABLE employee ALTER COLUMN email VARCHAR(100) DEFAULT 'test@test.com' 

И, наконец, колонку можно удалить, если она тебе не нужна:

 ALTER TABLE employee DROP COLUMN email 

6.3 Добавление и удаление первичного ключа

И еще несколько полезных примеров.

Допустим, мы забыли объявить колонку id первичным ключом. Всегда можно сделать это отдельно через ALTER TABLE :

 ALTER TABLE employee ADD PRIMARY KEY (email); 
 ALTER TABLE employee DELETE PRIMARY KEY; 

Источник

Оцените статью