Why does strftime() insert string into integer column - android

I have a 'created' column which is INTEGER and this is how I insert sqlite date into it:
ContentValues vals = new ContentValues();
vals.put(Column._CREATED_DATE, "strftime('%s','now')");
db.insert(Table.ARTICLE.name, null, vals);
Unbelievably he inserts strftime('%s','now') string into INTEGER column!
What the heck?
EDIT: when I run insert into article (created) values (strftime("%s","now")) in an SQLite browser, proper integer value is inserted...

Add a default value to your table instead, e.g.
CREATE TABLE article (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
_created_date INTEGER DEFAULT (strftime('%s', 'now'))
);
This will put unix epoch in _created_date if you do not set its column value when creating the row. If you want a timestamp (e.g. 2012-05-07 13:07:58) you define it as
_created_date INTEGER DEFAULT CURRENT_TIMESTAMP

Related

Android - Change a column type in SQLite database dynamically at runtime

I have an application, where I am detecting the type of a particular column at run-time, on page load. Please refer the below code:
public String fncCheckColumnType(String strColumnName){
db = this.getWritableDatabase();
String strColumnType = "";
Cursor typeCursor = db.rawQuery("SELECT typeof (" + strColumnName +") from tblUsers, null);
typeCursor.moveToFirst();
strColumnType = typeCursor.getString(0);
return strColumnType;
}
The above method simply detects the type of column with column Name 'strColumnName'. I am getting the type of column in this case.
Now, I want to change the column type to TEXT if I am receiving INTEGER as the column type. For this, I tried the below code:
public String fncChangeColumnType(String strColumnName){
db = this.getWritableDatabase();
String newType = "";
Cursor changeCursor = db.rawQuery("ALTER TABLE tblUsers MODIFY COLUMN " + strColumnName + " TEXT", null);
if (changeCursor != null && changeCursor.moveToFirst()){
newType = changeCursor.getString(0);
}
return newType;
}
But while executing the 'fncChangeColumnType' method, I am getting this error, android.database.sqlite.SQLiteException: near "MODIFY": syntax error (code 1): , while compiling: ALTER TABLE tblUsers MODIFY COLUMN UserID TEXT
NOTE: I also replaced 'MODIFY' with 'ALTER', but still getting the same error.
Please check if this is the right method to change the type dynamically.
Please respond back if someone has a solution to this.
Thanks in advance.
In brief, the solution could be :-
Do nothing (i.e. take advantage of SQLite's flexibility)
you could utilise CAST e.g. CAST(mycolumn AS TEXT) (as used below)
Create a new table to replace the old table.
Explanations.
With SQLite there are limitations on what can be altered. In short you cannot change a column. Alter only allows you to either rename a table or to add a column. As per :-
SQL As Understood By SQLite - ALTER TABLE
However, with the exception of a column that is an alias of the rowid column
one defined with ?? INTEGER PRIMARY KEY or ?? INTEGER PRIMARY KEY AUTOINCREMENT or ?? INTEGER ... PRIMARY KEY(??) (where ?? represents a valid column name)
you can store any type of value in any type of column. e.g. consider the following (which stores an INTEGER, a REAL, a TEXT, a date that ends up being TEXT and a BLOB) :-
CREATE TABLE IF NOT EXISTS example1_table (col1 BLOB);
INSERT INTO example1_table VALUES (1),(5.678),('fred'),(date('now')),(x'ffeeddccbbaa998877665544332211');
SELECT *, typeof(col1) FROM example1_table;
The result is :-
As such is there a need to change the column type at all?
If the above is insufficient then your only option is to create a new table with the new column definitions, populate it if required from the original table, and to then replace the original table with the new table ( a) drop original and b)rename new or a) rename original, b) rename new and c) drop original)
e.g. :-
DROP TABLE IF EXISTS original;
CREATE TABLE IF NOT EXISTS original (mycolumn INTEGER);
INSERT INTO original VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(0);
-- The original table now exists and is populated
CREATE TABLE IF NOT EXISTS newtable (mycolumn TEXT);
INSERT INTO newtable SELECT CAST(mycolumn AS TEXT) FROM original;
ALTER TABLE original RENAME TO old_original;
ALTER TABLE newtable RENAME TO original;
DROP TABLE IF EXISTS old_original;
SELECT *,typeof(mycolumn) FROM original;
The result being :-
i think the sql query statement is wrong ,try
ALTER TABLE tblUsers MODIFY COLUMN id TYPE integer USING (id::integer);
instead of id use column name....
hope this helps....
EDIT:
"ALTER TABLE tblUsers MODIFY COLUMN "+strColumnName+" TYPE integer USING ("+strColumnName+"::integer);"

How is it possible to insert row into SQLite table without specifying value for the primary key

I'm working on a project and don't understand this part of this code that I found online. (I have also looked at other examples and they do the exact same thing but I don't quite understand why)
When they are inserting something into the table, they have no value for the primary key. Could someone explain to me why that is the case?
Here is 2 examples of code that I found that do what I have stated above.
Thanks.
// As you can see a contact has 3 attributes.
int _id;
String _name;
String _phone_number;
// Where they create a table. As you can see the primary key is ID
#Override
public void onCreate(SQLiteDatabase db)
{
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Adding new contact
// This is what I don't understand. Why don't they get an ID for the contact.
// They only have values for the name and phone number when they insert it into the table.
public void addContact(Contact contact)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
Here's another example but this is using a book.
A book has 3 attributes, an id (the primary key), an author and the book name. And once again, they don't get the value for the primary key.
public void addBook(Book book)
{
Log.d("addBook", book.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_TITLE, book.getTitle()); // get title
values.put(KEY_AUTHOR, book.getAuthor()); // get author
// 3. insert
db.insert(TABLE_BOOKS, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// 4. close
db.close();
}
because primary key is Autoincrement as it is an alias for ROWID.
from the documentation:
In SQLite, table rows normally have a 64-bit signed integer ROWID
which is unique among all rows in the same table. (WITHOUT ROWID
tables are the exception.)
You can access the ROWID of an SQLite table using one the special
column names ROWID, ROWID, or OID. Except if you declare an ordinary
table column to use one of those special names, then the use of that
name will refer to the declared column not to the internal ROWID.
If a table contains a column of type INTEGER PRIMARY KEY, then that
column becomes an alias for the ROWID. You can then access the ROWID
using any of four different names, the original three names described
above or the name given to the INTEGER PRIMARY KEY column. All these
names are aliases for one another and work equally well in any
context.
When a new row is inserted into an SQLite table, the ROWID can either
be specified as part of the INSERT statement or it can be assigned
automatically by the database engine. To specify a ROWID manually,
just include it in the list of values to be inserted. For example:
so in the examples you have given id is being assigned by database engine. for most of the use cases this is good enough.
You can create the table like
static final String DATABASE_CREATE = "create table "+TABLE_NAME+"( ID integer primary key autoincrement,user_name text,user_phone text,user_email text); ";
Then it will increment automatically
See this link http://www.freakyjolly.com/android-sqlite-integration/
http://www.freakyjolly.com/android-sqlite-how-to-insert-rows-in-database/

Android SQLite replace into not working

I have this sql query. But row with id=1 won't replace.
CREATE TABLE IF NOT EXISTS `vergi_testler` (
`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`sual` text,
`cavab1` text,
`cavab2` text,
`cavab3` text,
`cavab4` text,
`d_cavab` INTEGER,
`verilib` INTEGER
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_neyse ON vergi_testler (_id);
REPLACE INTO `vergi_testler` VALUES (1, 'aaaa', 'aaa1', 'aaa1', 'aaa3', 'aaa4', 2, 0);
Supply column name INSERT OR REPLACE INTOvergi_testler(_id,sual,cavab1,cavab2,cavab3,cavab4,d_cavab,verilib) with table name in Query
so try
CREATE UNIQUE INDEX IF NOT EXISTS idx_neyse ON vergi_testler (_id,sual,cavab1,cavab2,cavab3,cavab4,d_cavab,verilib);
INSERT OR REPLACE INTO `vergi_testler`(_id,sual,cavab1,cavab2,cavab3,cavab4,d_cavab,verilib) VALUES (1, 'aaaa', 'aaa1', 'aaa1', 'aaa3', 'aaa4', 2, 0);
I found what is the problem. If you want to change something in your database you must do it in onUpgrade() method.

How to skip the primary key when inserting ContentValues in SQLiteDatabase

I have a little Problem with an insert-Statement in my Android-App.
Here is the code:
public void addNote(Note noteItem, int modulNummer){
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NOTE, noteItem.getNote());
cv.put(COLUMN_NOTEBESCHREIBUNG, noteItem.getBeschreibung());
cv.put(COLUMN_MODULID_FK, modulNummer);
db.insert(NOTETABLE, null, cv);
}
Now my problem. The first column in my table is an auto increment pk. And so i want to skip the first column and i want to begin the insert in the second column. How can i skip this first column?
Update
I've already deleted the .put for the first column. "COLUMN_NOTE" is my second column.
My table-structure looks like this:
id INTEGER AUTO INCREMENT
note double
beschreibung TEXT
modul_id INTEGER
UPDATE 2
I don't know why, but now it works. Thx for your help guys.
If you have a table like the following one:
private final String TAB_GROUP_ADD = "CREATE TABLE groups (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, description TEXT NOT NULL);";
And you use the following insert command:
ContentValues values = new ContentValues();
values.put(K_TITLE, title);
values.put(K_DESCRIPTION, description);
db.insert(TAB_GROUP, null, values);
Everything should go fine. The primary key field "id" will no be filled in by Java and the SQLite Database will do it for you.

SQLite and Android Insert/Updates on SQLiteDatabase -CompiledStatements-

Pretend I have a table with 2 columns. _id and name. _id is the primary key and I do not want to set this value manually. I want to perform an insert of name="john," and let the program create my own _id. I am unclear what "index" to use when inserting and how many question marks to use. Does this code do the job? Should the index for john be 1 or 2?
String TABLENAME = "table";
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(?);");
statement.bindString(1,"john");
statement.executeInsert();
Next, say I want to manually set my own _id value. Would I change the code to:
String TABLENAME = "table";
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(?,?);");
statement.bindLong(1,666); //Manual _id.
statement.bindString(2,"john");
statement.executeInsert();
Your first example where you provide only the name will not work:
sqlite> create table test (i integer primary key autoincrement, j text);
sqlite> insert into test values ('asd');
Error: table test has 2 columns but 1 values were supplied
sqlite> insert into test values (null, 'asd');
sqlite> select * from test;
1|asd
sqlite> insert into test (j) values ('asd');
sqlite> select * from test;
1|asd
2|asd
so you need to identify the name column as the destination of the sole value this way, (or as you mentioned in your comment pass null):
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" (name) VALUES(?);");
Your second example should work fine.
This would apply to some table created this way:
create table SomeTable (_id integer primary key autoincrement, name text)
Then
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(null,?);");
statement.bindString(1,"john");
Should also work.

Categories

Resources