SQLite应用之路---删除字段

前端之家收集整理的这篇文章主要介绍了SQLite应用之路---删除字段前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

sqlite应用之路---删除

@H_403_2@

@H_403_2@sqlite,并不支持列的删除,所以我们只能“曲线救国”。

@H_403_2@

@H_403_2@

1.思路

@H_403_2@1)我们通过临时表来实现,首先我们创建和目标表结构的临时表(除去要删除的字段);

@H_403_2@2)把目标表中的数据放入临时表;

@H_403_2@3)然后我们将目标表删除drop),并重新创建(除去要删除的字段,和原来的目标表结构一样);

@H_403_2@4)我们把临时表中的数据放回目标表,并删除临时表。

@H_403_2@

2.例子

@H_403_2@目标表target_table(id int primary key,nametext,sex text,age int);

@H_403_2@

@H_403_2@//其中sex字段是要被删除的字段

@H_403_2@步骤(1):创建临时表

@H_403_2@create temp table temp_target_table(id int primary key,name text,age int);

@H_403_2@步骤(2):保存数据

@H_403_2@insert into temp_target_table(id,name,age)select id,age from target_table

@H_403_2@步骤(3删除目标表,并重创建

@H_403_2@drop table target_table;

@H_403_2@create table target_table(id int primarykey,age int);

@H_403_2@步骤(4)将数据放回目标表,并删除临时表

@H_403_2@insert into target_table(id,age from temp_target_table;

@H_403_2@drop table temp_target_table;


@H_403_2@

@H_403_2@

3.来自官网

@H_403_2@sqlite,关于删除字段这一点,这里我放上sqlite官网上的解释:

@H_403_2@我是一个链接

@H_403_2@sqlite has limitedALTERTABLEsupport that you can use to add a column to the end of atable or to change the name of a table. If you want to make more complexchanges in the structure of a table,you will have to recreate the table. Youcan save existing data to a temporary table,drop the old table,create the newtable,then copy the data back in from the temporary table.

@H_403_2@For example,suppose you have a table named "t1" with columns names "a","b",and "c" and that you want to delete column"c" from this table. The following steps illustrate how this could bedone:

@H_403_2@BEGIN TRANSACTION;

@H_403_2@CREATE TEMPORARY TABLE t1_backup(a,b);

@H_403_2@INSERT INTO t1_backup SELECT a,b FROM t1;

@H_403_2@DROP TABLE t1;

@H_403_2@CREATE TABLE t1(a,b);

@H_403_2@INSERT INTO t1 SELECT a,b FROM t1_backup;

@H_403_2@DROP TABLE t1_backup;

@H_403_2@COMMIT;

猜你在找的Sqlite相关文章