I want to delete or add column in sqlite database
I am using following query to delete column.
ALTER TABLE TABLENAME DROP COLUMN COLUMNNAME
But it gives error
System.Data.SQLite.SQLiteException: SQLite error
near "DROP": syntax error
I want to delete or add column in sqlite database
I am using following query to delete column.
ALTER TABLE TABLENAME DROP COLUMN COLUMNNAME
But it gives error
System.Data.SQLite.SQLiteException: SQLite error
near "DROP": syntax error
I've wrote a Java implementation based on the Sqlite's recommended way to do this:
To get the table's column, I used the "PRAGMA table_info":
I actually wrote about it on my blog, you can see more explanations there:
http://udinic.wordpress.com/2012/05/09/sqlite-drop-column-support/
My solution, only need to call this method.
And auxiliary method to get the columns:
We cannot drop a specific column in SQLite 3. See the FAQ.
I rewrote the @Udinic answer so that the code generates table creation query automatically. It also doesn't need
ConnectionSource
. It also has to do this inside a transaction.As others have pointed out, sqlite's
ALTER TABLE
statement does not supportDROP COLUMN
, and the standard recipe to do this does not preserve constraints & indices.Here's some python code to do this generically, while maintaining all the key constraints and indices.
Please back-up your database before using! This function relies on doctoring the original CREATE TABLE statement and is potentially a bit unsafe - for instance it will do the wrong thing if an identifier contains an embedded comma or parenthesis.
If anyone would care to contribute a better way to parse the SQL, that would be great!
UPDATE I found a better way to parse using the open-source
sqlparse
package. If there is any interest I will post it here, just leave a comment asking for it ...This answer to a different question is oriented toward modifying a column, but I believe a portion of the answer could also yield a useful approach if you have lots of columns and don't want to retype most of them by hand for your INSERT statement:
https://stackoverflow.com/a/10385666
You could dump your database as described in the link above, then grab the "create table" statement and an "insert" template from that dump, then follow the instructions in the SQLite FAQ entry "How do I add or delete columns from an existing table in SQLite." (FAQ is linked elsewhere on this page.)