I want to add a column to a table in case the column doesn't exist,but SQLite doesn't seem to update the column list in Android
currently i'm using:
DB.execSQL("alter table "+table_name+" add column "+column_name+" text");
DB.rawQuery("select * from "+table_name+" limit 1",null).getColumnNames();
but the string list returned from "getColumnNames" does not contain the column I just created, so when I check again for the same column, it understands the column doesn't exist and tries to create it again, which causes a "duplicated column" exception
Thanks in advance for any help,this is my first question in SO :)
You need to increase the database number, which will call onUpgrade on your next app launch. In your onUpgrade method, you run the SQLite command to alter the table.
See here for some examples.
Try to discard the result of the first query after the "alter table" command and use the result of a second query. It worked for me.
Related
i have two tables, an FP_master table and a Take_Away_pack_details table. my first code below successfully copies data to column TakeAwayPkCost in table FP_master from column Pack_Cost in table Take_Away_Pack_Details.
In the second case I have a third table called View_Cart_Temp and I try to copy data from Column TakeAwayPKType in the FP_Master table to column Pack_type in the 3rd table View_Cart_temp. The 2nd piece of SQlite UPDATE code is shown below. The Syntax are identical in both cases and when i run this in my app, there is no error but the column is not updated. When I run this also in the DB Browser for SQLite, I get a message saying successfully updated but when i check the table its still null and no data has been copied. What could I be missing?
UPDATE FP_Master SET TakeAwayPkCost = (SELECT Pack_Cost FROM Take_Away_Pack_Details WHERE Pack_Type = TakeAwayPkType)
UPDATE View_Cart_Temp SET Pack_Type = (SELECT TakeAwayPkType FROM FP_Master WHERE Item = SKU)
How do I alter column in sqlite?
This is in Postgresql
ALTER TABLE books_book ALTER COLUMN publication_date DROP NOT NULL;
I believe there is no ALTER COLUMN in sqlite at all, only ALTER TABLE is supported.
Any idea? Thanks!
There's no ALTER COLUMN in sqlite.
I believe your only option is to:
Rename the table to a temporary name
Create a new table without the NOT NULL constraint
Copy the content of the old table to the new one
Remove the old table
This other Stackoverflow answer explains the process in details
While it is true that the is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of dangerous commands:
PRAGMA writable_schema = 1;
UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
PRAGMA writable_schema = 0;
You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.
For example:
Y:\> **sqlite3 booktest**
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> **create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT
NULL);**
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**
Error: BOOKS.publication_date may not be NULL
sqlite> **PRAGMA writable_schema = 1;**
sqlite> **UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT
NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';**
sqlite> **PRAGMA writable_schema = 0;**
sqlite> **.q**
Y:\> **sqlite3 booktest**
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**
sqlite> **.q**
REFERENCES FOLLOW:
pragma writable_schema
When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.
[alter table](From http://www.sqlite.org/lang_altertable.html)
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.
BEGIN TRANSACTION;
CREATE TEMPORARY TABLE t1_backup(a,b);
INSERT INTO t1_backup SELECT a,b FROM t1;
DROP TABLE t1;
CREATE TABLE t1(a,b);
INSERT INTO t1 SELECT a,b FROM t1_backup;
DROP TABLE t1_backup;
COMMIT
For more detail you can refer the link.
CREATE TABLE temp_Table(x,y[,etc]);
INSERT INTO temp_Table SELECT * FROM Table;
DROP TABLE Table;
ALTER TABLE temp_Table RENAME TO Table;
Thanks for helping me to find a definitive method!
ALTER COLUMN does not exist in SQLite.
Only Supported alter operations:
Alter Table Name
Alter Table Column Name
Add New Column
Drop Column
Alex Jasmin's answer shows possible way
Reference:
Sqlite Alter Table
Currently i have a database in android sqllite with many tables of the following column, column A and column B.
Now i am required to have table of column A , column B and column C for subsequent future table created in database. It is alright for me to keep old table of column A and B without changing anything.
so i have the following concern.
1 Let say i have the following code
rssiDB.execSQL("CREATE TABLE IF NOT EXISTS " + rssiTableName + " (ssid VARCHAR, bssid VARCHAR , rssi INTEGER )" );
What is the meaning of if not exists. If i am trying to create a table with a table name that already exists but different number of column, will the creation of table be successful? What will happen actually.
for example i have this table of the table name testing20 with column value of a743954759 , -40
and now i want to create a table of the table name testing20 with column value of peterwifi,a7954759 , -60
will the above code create a table with the same name but different number of column.
2 In a database, is it allowed for database to have many table of different column or is it compulsory for database to have every table to have the exact number of column or column name.
Let say i have a database with one table of table name testing1 with column A and column B. can i now add a table with table name testing2 with column A, column B and column C to the database.
I know i can try this out to find out myself. However i am afraid that it will affect my existing table if i try it out.
Hope someone can answer my question. Thank you
Table are unique objects in database, so you can define two tables with the same name. But you can alter existing tables and add new columns using ALTER TABLE function on your onUpgrade() method, like this :
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
}
}
Refere to this question How to add new Column to Android SQLite Database? for more info
I have a table "Items" with different columns but I didn't asign a name in each column. Now I have different rows in this table and I would like to execute:
ItemsDao.queryBuilder().where().eq(Items.NAME, "computer").query();
But my column doesn't have name. I have tried to update my table with "alter table" but it doesn't work.
AnyBody know how I can add a name of my column without lost my information?
Thank you
Edit:
Sorry, now I understand the question. You are saying that you did not specify a columnName = "..." for each of your fields and you are having problems with QueryBuilder now because of this.
You don't need a columnName to get QueryBuilder to work although it is recommended. You should be able to go back to fields and add a columnName static that matches your existing schema. For example, if the field in the database is "items" then you just add the columnName = "items" to your Java field. I don't believe Sqlite is case sensitive with regards to column names but it would be good to match the case as well.
But you don't need the columnName. If you field name in the database is "items" then you should be able to do:
itemsDao.queryBuilder().where().eq("items", "computer").query();
If you edit your question to show your schema and the exception you are getting from QueryBuilder, I'll be able to respond more specifically.
I believe you should be able to do:
dao.executeRaw("ALTER TABLE `items` ADD COLUMN name VARCHAR;");
That doesn't work for you? There is a section in the ORMLite documentation about updating your schema under Android:
http://ormlite.com/docs/upgrade-schema
To quote from it, you will need to change your database version when you make schema changes and then in your onUpgrade(...) method do something like:
Dao<Account, Integer> dao = getHelper().getAccountDao();
// change the table to add a new column named "age"
dao.executeRaw("ALTER TABLE `account` ADD COLUMN age INTEGER;");
Most likely you will be keying off the database version number do if they have version 1 you do X and Y but if they have version 2 you just do Y. Something like that:
if (oldVersion == 1) {
// we added the age column in version 2
dao.executeRaw("ALTER TABLE `account` ADD COLUMN age INTEGER;");
}
if (oldVersion < 2) {
// we added the weight column in version 3
dao.executeRaw("ALTER TABLE `account` ADD COLUMN weight INTEGER;");
}
You are limited by Sqlite on what you can do with ALTER TABLE. Right now you can only rename a column or add a new column. See the docs for more details.
If you want to change the database, in your SQLiteOpenHelper you should:
change database version
override "onUpgrade" to make the changes you
want
change onCreate method, this way new users will have the good version of your database, not the old one
If there are big structural changes, in onUpgrade you copy the useful information in new database and drop the old database.
Hope it helps:)
I have a databse with three tables.
The first table is something like:
_id user
The second table:
_id route user_id
and user_id is exactly the _id from the first table.
So when I insert in the first tabel a new record,I should keep the _id in order to insert it
in the second table.But how could I keep something that is autoincremented and given by the database?:-S
The SQLiteDatabase has an insert() method, which returns the _id you are looking for.
There may be a better way, but you could grab (query for) the _id field right after you do your commit to the first table. Then you will have the user_id for use in the second table.