SQLite script vars - android

I need to mass populate my SQLite database — ideally using a script rather than code.
I would like to do this (MySQL syntax) but for SQLite but I'm not sure it you can have variables defined in scripts:
INSERT INTO `parent` (id, name) values(NULL, "some name!");
SET #parentId= last_insert_rowid();
INSERT INTO `child` (id, parentId, name, ) values (NULL, #parentId, 'some name!);
SQLite throws errors when I try to declare variables in my SQLite script. Can this be done in SQLite?

You can use the function last_insert_rowid() without a script var for this case:
insert into parent (id, name) values (NULL, 'some name!');
then:
insert into child (id, parentId, name) values (NULL, last_insert_rowid(), 'child name!');
transcript:
SQLite version 3.7.6.3
sqlite> create table parent (id integer primary key, name);
sqlite> create table child (id integer primary key, parentId integer, name);
sqlite> insert into parent (id, name) values (NULL, 'some name!');
sqlite> insert into child (id, parentId, name) values (NULL, last_insert_rowid(), 'child name!');
sqlite> select * from parent;
1|some name!
sqlite> select * from child;
1|1|child name!
sqlite>
If you need to keep the value around for a while (through multiple inserts for example) use a temporary table:
sqlite> create temp table stash (id integer primary key, parentId integer);
sqlite> insert into parent (id, name) values (NULL, 'another name!');
sqlite> replace into stash values (1, last_insert_rowid());
sqlite> insert into child (id, parentId, name) values (NULL, (select parentID from stash where id = 1), 'also a name!');
sqlite> select * from parent;
1|some name!
2|another name!
sqlite> select * from child;
1|1|child name!
2|2|also a name!
sqlite>

Unfortunately you can't declare such variable in SQLite script. Moreover AFAIK all statements will not be executed except the first one. Also look HERE

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);"

Can you set a column equal to another column in a table using SQLiteDatabse update()?

I need to make a column equal to another column in the table. I can't figure it out using the update method of my SQLiteDatabase.
I know the SQL statement is:
UPDATE coolTable SET columnA = columnB;
Do I put it in the ContentValues I pass the function? or the selection string?
You can use update() only to set literal values (as bind params), not any other kind of expression supported by sqlite SQL syntax.
Use execSQL() to execute your raw UPDATE query with column name expression.
execSQL() with error checking:
SQLiteDatabase db = getReadableDatabase();
try {
long count = DatabaseUtils.queryNumEntries(db, "pweb");
db.execSQL("update pweb set h_id = _id;");
long rows = DatabaseUtils.longForQuery(db, "SELECT changes()", null);
if(count != rows ) Log.e("wrong count","update failed");
}
catch(SQLException e){
Log.e("SQLException","update failed");
}
db.close();
but I was wondering if it is possible to use the database's update()
function instead of execSQL()
You can use sqlite3 to view and manipulate you data, and test out sql commands.
Create a table:
CREATE TABLE pweb (_id INTEGER PRIMARY KEY,h_id INTEGER ,sent INTEGER);
See the original rows:
sqlite> select * from pweb;
1|10|1
2|20|1
3|30|0
4|40|0
execute a column update:
sqlite> update pweb set h_id = _id;
See the changes to all rows:
sqlite> select * from pweb;
1|1|1
2|2|1
3|3|0
4|4|0
Something more complex ?
sqlite> update pweb set h_id = _id + 1;
result:
sqlite> select * from pweb;
1|2|1
2|3|1
3|4|0
4|5|0
See also Understanding SQLITE DataBase in Android:

SQLite query doesn't work as expected

I have a problem with an SQLite Query and can't figure it out. These are my table:
CREATE TABLE Exercise
(
e_id int auto_increment primary key,
name varchar(20)
);
CREATE TABLE PersonalList
(
p_id int auto_increment primary key,
name varchar(20)
);
CREATE TABLE Exercise_Personal_List
(
e_id_m int auto_increment primary key,
p_id_m int
);
INSERT INTO Exercise
(e_id, name)
VALUES
('1', 'exercise1'),
('2', 'exercise2'),
('3', 'exercise3'),
('4', 'exercise4'),
('5', 'exercise5'),
('6', 'exercise6');
INSERT INTO PersonalList
(p_id, name)
VALUES
('1', 'list1'),
('2', 'list2'),
('3', 'list3');
INSERT INTO Exercise_Personal_List
(e_id_m, p_id_m)
VALUES
('2', '1'),
('4', '1'),
('6', '1'),
('1', '2');
Exercise table: a collection of exercises
PersonalList table: a collection of list
Exercise_Personal_List: a reference to which Exercise is part of which Exercise_Personal_List
I'm trying to get a list of Exercises that are not yet added to a specific list. E.g. the ones that are not added to List 1. My query:
select * from Exercise
where e_id not in (
select e_id from Exercise_Personal_List
where p_id_m like '1'
)
The result is empty. I don't see the error in the query. The correct result should be 1, 3, 5.
Btw, I'm using http://sqlfiddle.com to evaluate this stuff. It's faster for testing :)
Thanks for your help!
I think you mean to be doing the following query where the second instance of e_id has been changed to e_id_m:
select * from Exercise
where e_id not in (
select e_id_m from Exercise_Personal_List
where p_id_m like '1'
)
There is a little mess up in the creation - you shouldn't use auto_increment in the joining table:
CREATE TABLE Exercise_Personal_List
(
e_id_m int,
p_id_m int
);
And the selection should be:
select * from Exercise
where e_id not in (
select e_id_m as e_id from Exercise_Personal_List
where p_id_m like '1'
)

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.

Increase a column value in sqlite without the method execSQL

I'd like to update one of my table's column with the following query:
update TABLE set COLUMN_NAME= COLUMN_NAME+1;
using if posible the
update(String table, ContentValues values, String whereClause, String[] whereArgs)
method in SQLiteDatabase class in android
Is that posible?
Thanks in advance
though this is a bit overdue, i'm just adding an example that works...
SQLite version 3.7.9 2011-11-01 00:52:41
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table test1(a int primary key, b int);
sqlite> begin transaction;
sqlite> insert into test1(a,b) values (1,4);
sqlite> insert into test1(a,b) values (2,5);
sqlite> insert into test1(a,b) values (3,4);
sqlite> commit;
sqlite> select * from test1;
1|4
2|5
3|4
sqlite> update test1 set b=b+1;
sqlite> select * from test1;
1|5
2|6
3|5
sqlite> update test1 set b=b+10;
sqlite> select * from test1;
1|15
2|16
3|15
sqlite>
You may have some luck with execSQL. Here's what I did to solve a similar problem:
db.beginTransaction();
try {
//do update stuff, including execSQL()
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
See also https://stackoverflow.com/a/5575277/6027

Categories

Resources