首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在SQLITE中删除或添加列?

如何在SQLITE中删除或添加列?
EN

Stack Overflow用户
提问于 2011-12-09 15:03:56
回答 13查看 323.7K关注 0票数 285

我想在sqlite数据库中删除或添加列

我正在使用以下查询来删除列。

代码语言:javascript
复制
ALTER TABLE TABLENAME DROP COLUMN COLUMNNAME

但它会给出错误

代码语言:javascript
复制
System.Data.SQLite.SQLiteException: SQLite error
near "DROP": syntax error
EN

回答 13

Stack Overflow用户

发布于 2012-05-14 18:12:32

我已经基于Sqlite推荐的方式编写了一个Java实现:

代码语言:javascript
复制
private void dropColumn(SQLiteDatabase db,
        ConnectionSource connectionSource,
        String createTableCmd,
        String tableName,
        String[] colsToRemove) throws java.sql.SQLException {

    List<String> updatedTableColumns = getTableColumns(tableName);
    // Remove the columns we don't want anymore from the table's list of columns
    updatedTableColumns.removeAll(Arrays.asList(colsToRemove));

    String columnsSeperated = TextUtils.join(",", updatedTableColumns);

    db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tableName + "_old;");

    // Creating the table on its new format (no redundant columns)
    db.execSQL(createTableCmd);

    // Populating the table with the data
    db.execSQL("INSERT INTO " + tableName + "(" + columnsSeperated + ") SELECT "
            + columnsSeperated + " FROM " + tableName + "_old;");
    db.execSQL("DROP TABLE " + tableName + "_old;");
}

为了获取表的列,我使用了"PRAGMA table_info":

代码语言:javascript
复制
public List<String> getTableColumns(String tableName) {
    ArrayList<String> columns = new ArrayList<String>();
    String cmd = "pragma table_info(" + tableName + ");";
    Cursor cur = getDB().rawQuery(cmd, null);

    while (cur.moveToNext()) {
        columns.add(cur.getString(cur.getColumnIndex("name")));
    }
    cur.close();

    return columns;
}

实际上我在我的博客上写过,你可以在那里看到更多的解释:

http://udinic.wordpress.com/2012/05/09/sqlite-drop-column-support/

票数 48
EN

Stack Overflow用户

发布于 2011-12-09 15:07:58

http://www.sqlite.org/lang_altertable.html

如图所示,仅支持ADD COLUMN。不过,有一个(有点繁重)的解决方法:http://www.sqlite.org/faq.html#q11

票数 13
EN

Stack Overflow用户

发布于 2012-09-26 15:12:27

我们不能删除SQLite 3中的特定列。请参阅FAQ

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8442147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档