我想在sqlite数据库中删除或添加列
我正在使用以下查询来删除列。
ALTER TABLE TABLENAME DROP COLUMN COLUMNNAME
但它会给出错误
System.Data.SQLite.SQLiteException: SQLite error
near "DROP": syntax error
发布于 2012-05-14 18:12:32
我已经基于Sqlite推荐的方式编写了一个Java实现:
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":
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/
发布于 2011-12-09 15:07:58
http://www.sqlite.org/lang_altertable.html
如图所示,仅支持ADD COLUMN。不过,有一个(有点繁重)的解决方法:http://www.sqlite.org/faq.html#q11
发布于 2012-09-26 15:12:27
我们不能删除SQLite 3中的特定列。请参阅FAQ。
https://stackoverflow.com/questions/8442147
复制相似问题