分享

SQlite在已创建的表中删除一列--解决方案

 豆芽爱尚阅 2015-12-12

sqlite中是不支持删除列操作的,所以网上alter table table_name drop column col_name这个语句在sqlite中是无效的,而替代的方法可以如下:

1.根据原表创建一张新表

2.删除原表

3.将新表重名为旧表的名称

示例例子如下

1.创建一张旧表Student,包含id(主码),name, tel

create table student (

id integer primary key,

name text,

tel text

)

2.给旧表插入两个值

insert into student(id,name,tel) values(101,"Jack","110")

insert into student(id,name,tel) values(102,"Rose","119")

结果如图

clip_image002

3.接下来我们删除电话这个列,首先根据student表创建一张新表teacher

create table teacher as select id,name from student

结果如图

clip_image004

可以看到tel这一列已经没有了

4.然后我们删除student这个表

drop table if exists student

5.将teacher这个表重命名为student

alter table teacher rename to student

结果演示:

select * from student order by name desc(desc降序, asc升序)

clip_image006

这样就可以得到我们想要的结果了。

另外:给自己一个提示,在android sqlite中的查询语句如果是text类型的别忘了给他加上””来指明是String类型的,例如:

Cursor c = mSQLiteDatabase.query(TABLE_NAME, null, NAME + "=" + "/"" + name + "/"", null, null,null, null);

 

方法二:

http://www./faq.html#q11

  1. SQLite has limited ALTER TABLE support that you can use to add a column to the end of a table or to change the name of a table. If you want to make more complex changes in the structure of a table, you will have to recreate the table. You can save existing data to a temporary table, drop the old table, create the new table, then copy the data back in from the temporary table.  
  2.   
  3. 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 be done:   
  4.   
  5. BEGIN TRANSACTION;  
  6. CREATE TEMPORARY TABLE t1_backup(a,b);  
  7. INSERT INTO t1_backup SELECT a,b FROM t1;  
  8. DROP TABLE t1;  
  9. CREATE TABLE t1(a,b);  
  10. INSERT INTO t1 SELECT a,b FROM t1_backup;  
  11. DROP TABLE t1_backup;  
  12. COMMIT;  

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多