Modify a column in a table in Sqlite

Sqlite cannot modify columns like other databases, including renaming queues, deleting columns, modifying column attributes, etc.

For example, like mysql, it can directly use sql to operate a column in the table, such as:

alter table test drop column name; -- delete table column 

alter table test modify address char(10) -- modify table column type or alter table test change address address char(40) 

alter table test change column address address1 varchar(30)--modify table column name

These operations cannot be directly operated by Sqlite

How does Sqlite implement column modification? Here's an idea:

First, change the table you want to modify and change the table name to a temporary table:

如:ALTER TABLE "Student" RENAME TO "_Student_old_20140409";

Next, create a new table, the fields of the new table are the fields you need, and the data in the new table is the data in the temporary table, so as to ensure the integrity of the data:

Such as:

CREATE TABLE "Student" (

"Id"  INTEGER PRIMARY KEY AUTOINCREMENT,

"Name"  Text);

INSERT INTO "Student" ("Id", "Name") SELECT "Id", "Title" FROM "_Student_old_20140409";

In this way, it is a bit troublesome to modify the column indirectly.


Some methods are direct, which inserts data into the new table at the same time, such as:

create table Student as select Id,Name from _Student_old_20140409;

The Student obtained in this way also has data, and the columns of the table can also meet our needs.

But there is a problem that the Student table obtained in this way has no indexes at all, including the primary key index, so you need to add the primary key index and other required indexes by yourself.


In addition, attach the Sqlite command operation manual: http://www.runoob.com/sqlite/sqlite-index.html


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324844528&siteId=291194637