How to set a default value to a TEXT column in Sqlite? - android

I have a simple table. I'm trying to put a default value to a TEXT column. Here is the table query:
"CREATE TABLE book(_id INTEGER PRIMARY KEY AUTOINCREMENT, book_id TEXT NOT NULL DEFAULT '0', book_name TEXT NOT NULL);"
It creates the table but the problem occurs when i try to insert a data. I was only trying with giving a book name to book_name, as i expected that the book_id would have a default value 0 to the column. But it doesn't and it adds the null value, so the row doesn't get inserted. I have also tried with this query:
"CREATE TABLE book(_id INTEGER PRIMARY KEY AUTOINCREMENT, book_id TEXT NOT NULL DEFAULT \'0\', book_name TEXT NOT NULL);"
But the problem remains the same. I have searched the stack overflow, and got some answers but they are old and not working for me right now. So has something changed on how to set the default value to a TEXT column in sqlite. Thanks in advance :)
EDIT
Here is the insert statement:
database.insert("book", null, cv);
Here cv is the object of ContentValues which contains only the value for the column book_name.

You can specify a default value for the column when you create the table. (It doesn't appear as though you can add a default using an ALTER statement, so you'll have to recreate your table.)
CREATE TABLE your_table_name
(MainContactName TEXT NOT NULL DEFAULT '')
For Example,
CREATE TABLE book(_id INTEGER PRIMARY KEY AUTOINCREMENT,book TEXT DEFAULT "abc");
now see that , default value is set to "abc"
Check sqllite documentation.

To alter table,
sqlitedbInstance.execSQL("alter table myTable add column Address TEXT DEFAULT 'ABC' ");

Related

NOT NULL constraint failed while copying data to a new table

I migrate my database from SQLiteOpenHelper to Room.
I have a table that I want to change, lets call it "my_table".
Its simplified create statement:
CREATE TABLE `my_table`
(`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`title` TEXT
)
During an upgrade among other changes I add the new column type INTEGER NOT NULL (I'm adding Foreign Key aswell and doing other significant changes, that's the reason to create a new table instead of altering the existing one):
CREATE TABLE "new_table"
(`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`title` TEXT,
`type` INTEGER NOT NULL
)
Then I want to copy data from the my_table to the new_table and set type column's values.
SQL statement:
INSERT INTO new_table (title)
SELECT title FROM my_table;
UPDATE new_table SET type = 1;
DROP TABLE my_table;
ALTER TABLE new_table RENAME TO my_table;
Android migration:
public static final Migration MIGRATION_TEST = new Migration(1, 2) {
#Override
public void migrate(#NonNull SupportSQLiteDatabase database) {
// Create new table
database.execSQL("CREATE TABLE new_table (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `title` TEXT, `type` INTEGER NOT NULL)");
// Copy some data
database.execSQL("INSERT INTO new_table (title) SELECT title FROM old_table"); // constraint violation
// Insert default value into the measures column
database.execSQL("UPDATE new_table SET type = 1");
// Delete old table
database.execSQL("DROP TABLE old_table");
// Rename new table
database.execSQL("ALTER TABLE new_table RENAME TO my_table");
}
};
Obviously I get NOT NULL constraint failed: new_table.type error:
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: new_table.type (code 1299)
Error Code : 1299 (SQLITE_CONSTRAINT_NOTNULL)
Caused By : Abort due to constraint violation.
(NOT NULL constraint failed: new_table.type (code 1299))
I can avoid it by changing new table's create statement and setting default value for the type column.
CREATE TABLE "new_table"
(`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`title` TEXT,
`type` INTEGER NOT NULL DEFAULT 1
)
But I don't want to do this as Room doesn't suport default values out of the box and in order to avoid future mistakes when inserting new values into tables.
Are there any workarounds to avoid this error while inserting data to a new table?
I think the following may work :-
database.execSQL("INSERT INTO new_table (title,type) SELECT title, 1 FROM old_table");
That is, you are now saying to INSERT 2 columns as per the SELECT statement. The SELECT returns 2 values the title from the old_table and the literal value 1.
That is SELECT actual returns the result of expressions result-column which aren't limited to just columns. An Expression can be literal value, result of functions, results of operations and other expr
As per
The list of expressions between the SELECT and FROM keywords is known
as the result expression list.
SQL As Understood By SQLite - SELECT - 3. Generation of the set of result rows.
You then wouldn't need database.execSQL("UPDATE new_table SET type = 1").

Is the sequence on how we type a Sqlite query to Create a column with attributes really matters

I'm new to coding android apps with Sqlite
I have three questions
I created this Sqlite table with columns with attributes like
TEXT
NOT NULL
UNIQUE
DEFAULT regular
Q1) I'm skeptical to know whether is there any order on how to delare attributes for a row
Q2) If I declare any row to have a default value like will the text be still inserted even though the user inserts something in that row, if yes, then how to insert a default value if the user dosen't inset any value in a specific Row
Q3)Is my code below correct ? What I desire is the row KEY_TAGNAME to be unique, not null and to have a value if the row doesn't get any data while a insert statement occurs for that table.
private static final String CREATE_TAGTABLE_SQL=
"CREATE TABLE " + DATABASE_TABLE_TAG
+ " ("
+ KEY_TAGROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_TAGNAME + " TEXT NOT NULL UNIQUE DEFAULT regular"
+ ");";
A1: I couldn't find anything in the documentation that clearly says anything about the order of the attributes but I tried to create a couple of tables in a test database I created to check this and it seems that if you do not follow the proper order you will get a syntax error.
(tried with create table test (key1 integer primary key autoincrement) which works correctly but create table test1 (key1 primary key integer autoincrement) gives a near "integer": syntax error:
A2: You can have a default value inserted that will be put if the user does not input anything there. The keyword is default and you will find more info here on how to use it (TL;DR upon table's creation you will create the row as usual and in the end put a DEFAULT and next to it the value. Please check the link on this)
A3 Your query is correct and will do the things you mention.

android.database.sqlite.SQLiteException: near "ON": syntax error (code 1)

This is the MySQL code I am using on the server to create a table...
CREATE TABLE brand_names (
id int(7) unsigned NOT NULL AUTO_INCREMENT,
brand_name varchar(255) NOT NULL,
parent_company_id int(7) NOT NULL DEFAULT '0',
last_modified_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY brand_name (brand_name),
FULLTEXT KEY name (brand_name)
) ENGINE=MyISAM AUTO_INCREMENT=225 DEFAULT CHARSET=latin1
I am trying to replicate the same table in Android by using...
CREATE TABLE brand_names (
_id integer PRIMARY KEY AUTOINCREMENT,
brand_name text NOT NULL,
parent_company_id integer NOT NULL DEFAULT '0',
last_modified_on datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE SET DEFAULT
)
However, I am getting this exception...
android.database.sqlite.SQLiteException: near "ON": syntax error (code 1): , while compiling: CREATE TABLE brand_names (_id integer PRIMARY KEY AUTOINCREMENT, brand_name text NOT NULL, parent_company_id integer NOT NULL DEFAULT '0', last_modified_on datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE SET DEFAULT);
So there seems to be something wrong around the ON part. (NB - All I am trying to achieve with the ON clause is to make it so that when the row is updated, the last_modified_on datetime will be automatically set to the current time.
I've looked at this SQLite page, and it looks like my syntax is correct, but clearly something is wrong so I'm a bit stumped. Can anyone help resolve?
The correct one is,
CREATE TABLE brand_names (
_id integer PRIMARY KEY AUTOINCREMENT,
brand_name text NOT NULL,
parent_company_id integer NOT NULL DEFAULT '0',
last_modified_on datetime NOT NULL DEFAULT CURRENT_TIMESTAMP);
You are using ON UPDATE SET DEFAULT in the end which is wrong syntax.
The last_modified_on datetime will be automatically set to the current time by using DEFAULT CURRENT_TIMESTAMP.
What you have seen from the SQLite doc is totally different from what you want to achieve.
The following query will work assuming you have a parent table with id parent_company_id -
CREATE TABLE brand_names(_id integer PRIMARY KEY AUTOINCREMENT,
brand_name text NOT NULL, parent_company_id integer NOT NULL DEFAULT '0',
last_modified_on datetime NOT NULL REFERENCES parent(parent_company_id)
ON UPDATE SET DEFAULT);
This will update the parent_company_id (the parent key of the foreign key constraint) column of the parent record without breaking referential integrity between the two tables parent and brand_names.
An ON UPDATE action is only taken if the values of the parent key are modified so that the new parent key values are not equal to the old. So this is used to configure actions that take place when modifying the parent key values of existing rows (ON UPDATE). They are associated with each foreign key in an SQLite database.

How to get the value of an autoincreament field from SQLiteDatabase in Android?

I have a table in SQLiteDatabase with only one column which is autoincreament...
CREATE TABLE [LEADID] (
[lead_id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT
)
I want the value of autoincrement to start from 10000.
How do i get the value of this column???
How do i put an insert and a select statement to get the autoincreamented value??
i basically dont know how to invoke this table to generate this autoincrement value...
how do i do that??
Please help!!! thanks in advance!!
You can set new auto-increment starting value for table mytable using this:
UPDATE sqlite_sequence SET seq = 10000 WHERE name = 'mytable'
If your table already has primary key present with value that conflicts (like 10000), next insert will automatically change auto-increment value to max_value+1.

Android SQLite auto increment

I currently have a table called User which has a id column which is created as
'INTEGER PRIMARY KEY'
Lets say I have created two users so the table has id 1 and 2
If I delete the second user and create a third the id is 2, I need this to be 3
So it seems Android is selecting the next available id, how can I change this to its more like a sequence number?
Regards
Make it INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL. Here's what the docs say:
If a column has the type INTEGER PRIMARY KEY AUTOINCREMENT then... the ROWID chosen
for the new row is at least one larger than the largest ROWID that has
ever before existed in that same table.
The behavior implemented by the AUTOINCREMENT keyword is subtly
different from the default behavior. With AUTOINCREMENT, rows with
automatically selected ROWIDs are guaranteed to have ROWIDs that have
never been used before by the same table in the same database. And the
automatically generated ROWIDs are guaranteed to be monotonically
increasing.
SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto incrementing it.
The keyword AUTOINCREMENT can be used with INTEGER field only.
Syntax:
The basic usage of AUTOINCREMENT keyword is as follows:
CREATE TABLE table_name(
column1 INTEGER AUTOINCREMENT,
column2 datatype,
column3 datatype,
.....
columnN datatype,
);
For Example See Below:
Consider COMPANY table to be created as follows:
sqlite> CREATE TABLE TB_COMPANY_INFO(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
Now, insert following records into table TB_COMPANY_INFO:
INSERT INTO TB_COMPANY_INFO (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'MANOJ KUMAR', 40, 'Meerut,UP,INDIA', 200000.00 );
Now Select the record
SELECT *FROM TB_COMPANY_INFO
ID NAME AGE ADDRESS SALARY
1 Manoj Kumar 40 Meerut,UP,INDIA 200000.00
If speaking for ANDROID, yes, above answers are correct, except naming of the id column.
database.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " ( rowid INTEGER PRIMARY KEY AUTOINCREMENT, Raqam VARCHAR, ChandBor INT(3));");
It looks like in Android it should be named as 'rowid'.
And with Cursor you need to instantiate it like:
Cursor cursorLcl = database.rawQuery("SELECT *," + TableName + ".rowid AS rowid" + " FROM " +
TableName, null);
Otherwise it didnt work for me. I don't know why it so.
Just remember for android when writing tot the database (ie. executing),
do
INSERT INTO TABLE_NAME (param1name, param2name) VALUES (param1,param2)
and there is no need to add a place holder for the auto increment. It will add it by itself when adding a record. If you do not declare the params that you will put in, you will get the error x amount of variables expected and you only gave x-1, and this is because you are not supposed to give any place holding value for the auto increment column

Categories

Resources