I have a database with a table called 'connection', for simplicities' sake, let's say I only have one column which is called 'rowName'. Now let's say I add a row with rowName = a; now I add a row with rowName = q, and lastly I add a row with rowName = w (letters are completely random). Now, I irritate thru the results with the statement:
NSString * queryStatements = [NSString stringWithFormat:#"SELECT rowName, FROM tableName"];
and using the code:
NSMutableArray * rows = [[NSMutableArray alloc] init]; //create a new array
sqlite3_stmt * statement;
if(sqlite3_prepare_v2(databaseHandle, [queryStatements UTF8String], -1, &statement, NULL) == SQLITE_OK){
while (sqlite3_step(statement) == SQLITE_ROW){
NSString * rowName = [NSString stringWithUTF8String : (char*) sqlite_column_text(statement, 1)];
[rows addObject : connection];
} sqlite3_finalize(statement_;
}
In the array rows, will the object at index 0 be rowName = a, and at index 1 rowName=q, and at index 2 rowName = w? or will it be random? Is there a way to make it not-random?
Also, if i delete a row, will it have any affect on the other rows order?
Never depend on a sort order from your database. Always specify one if it is required.
SELECT rowName FROM tableName order by rowName
gives you the data sorted by rowName. If you need a different order, you need another column.
You can also sort your NSArray if need be.
What sort order are you looking for?
Related
Is it possible to execute two or more select statement in one query in SQLite? For example,
We can execute create or insert query,
NSString *create_query = #"create table if not exists Employee (id integer primary key, firstName text, lastName text);create table if not exists Department (id integer primary key, department text, devision text)";
By using,
sqlite3_exec(self.contactDB,[create_query UTF8String], NULL, NULL, &errorMessage) == SQLITE_OK)
we can execute it.
But if query is something like,
NSString *select_query = #"select * from Employee;select * from Department";
Then is it possible to execute? If yes then how to differentiate data from sqlite3_step?
Generally we are fetching data like,
if (sqlite3_prepare_v2(self.contactDB, [select_query UTF8String], -1, &statement, NULL) == SQLITE_OK) {
NSLog(#"prepared from data get");
while (sqlite3_step(statement) == SQLITE_ROW) {
NSString *department = [[NSString alloc]initWithUTF8String:(const char*)sqlite3_column_text(statement, 1)];
NSString *devision = [[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement, 2)];
NSLog(#"Department : %#, Devision : %#",department,devision);
}
NSLog(#"errror1 is %s",sqlite3_errmsg(self.contactDB));
}
But if there is a two select statement then how to identify column and row in sqlite3_step?
We can execute two select statements together (i.e. select * from Employee;select * from Department ) in terminal, so it should some way in iOS I think.
Yes, you can use sqlite3_exec() to execute two SELECT statements in one call. You just have to provide a callback function where you handle the result rows. I've never used that feature, and how I understand the doc you're on your own to distinguish the rows of each statement; perhaps one can use the column count for that.
I advise against using sqlite3_exec() that way; it seems rather tedious and error-prone. sqlite3_prepare_*() should be the way to go, and it can only handle one result set (SELECT query), but you can have open multiple statements at a time, represented by the ppStmt handle. If you have problems with that you should describe them instead of posting a XY Problem question.
We can perform this by using C style callback function with sqlite3_exec.
There is no proper code available on internet (I haven't found!) so i would like to answer with code sample.
We can implement C - style callback method like
int myCallback(void *parameter, int numberOfColumn, char **resultArr, char **column)
{
NSLog(#"number of column %d",numberOfColumn); // numberOfColumn is return total number of column for correspond table
NSString *columnName = [[NSString alloc]initWithUTF8String:column[0]]; // This will return column name column[0] is for first, column[1] for second column etc
NSLog(#"column name is %#",columnName);
NSString *result = [[NSString alloc]initWithUTF8String:resultArr[2]]; // resultArr returns value for row with respactive column for correspond table. resultArr[2] considered as third column.
NSLog(#"result is %#",result);
return 0;
}
And we can call this callback function in our sqlite3_exec function like,
NSString *getData = #"select * from Department;select * from Employee";
if (sqlite3_exec(self.contactDB, [getData UTF8String], myCallback, (__bridge void *)(self), &err) == SQLITE_OK ) {
if (err) {
NSLog(#"error : %s",err);
}
else {
NSLog(#"executed sucessfully");
}
}
We have make bride : (__bridge void *)(self) as parameter of sqlite3_exec. We can pass NULL in this case because we have implemented c style function. But if we implement Objective - c style function or method then we must pass (__bridge void *)(self) as parameter.
So, By callback function we can execute multiple queries in one statement whether it is select type queries or else.
Reference : One-Step Query Execution Interface
I am trying to order UITableView rows. I already implemented necessary methods and it works on my mutable array. However I don't know how can I apply this changes to my database.
My database has favs column
CREATE TABLE favs (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
w_name TEXT
);
I was using "insert or replace into favs (w_name) values ('%#%');" statement to insert new word to favs database. How can I change the id of two records so that I can list the favs values by order of id so that they will be sorted. For example I want to change my table from this
id|w_name
1|apple
2|banana
3|orange
to
id|w_name
1|apple
3|banana
2|orange
I can change the id if the key is not primary by using
UPDATE favs SET id = (CASE id WHEN 2 THEN 3 ELSE 2 END)
WHERE id IN (2, 3);
If I do like this I need to calculate id by myself each time I insert the record. So, how can re-order ids so that my changes in UITableView is reflected into database.
In all case, if you want to reorder you TableView, you've to reorder the array that feed the TableView.
You can execute the query again.
Or use that
yourArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(TYPE *p1, TYPE *p2){
return [p1 compare:p2];
}];
and finish with [tableView reloadData];
Add another column to your table and call it sort. There you will put the index of each record in your array [array indexOfObject:object]. Every time you want to save the order of your array you can update the sort column of each record e.g.
const char *sql = "UPDATE favs SET sort = ? WHERE id = ?";
if(sqlite3_prepare_v2(database, sql , -1, &updateStatment, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
sqlite3_bind_int(updateStatment, 1, [array indexOfObject:object]); sqlite3_bind_int(updateStatment, 2, [object id]);
I have a sqlite statement that provides me with a selected single row and 20 columns.
Up to now I've been using this while loop:
while(sqlite3_step(statement) == SQLITE_ROW) {
NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, an_incrementing_int)];
...
}
However the problem with this is as there is only one row it will naturally only return the 1st column.
So is there something like while.. == SQLITE_COLUMN ?
Thanks
To get number of column a query returns, use sqlite3_column_count.
Function to return column data, sqlite3_column_... all accept an 2nd argument which is int column index.
NSString coldata;
int i;
while(sqlite3_step(statement) == SQLITE_ROW) {
for (i=0; i<sqlite3_column_count(statement); ++i) {
coldata= [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];
}
}
Note also: take care using data pointer to column values!
The pointers returned are valid until a type conversion occurs as
described above, or until sqlite3_step() or sqlite3_reset() or
sqlite3_finalize() is called. The memory space used to hold strings
and BLOBs is freed automatically. Do not pass the pointers returned
from sqlite3_column_blob(), sqlite3_column_text(), etc. into
sqlite3_free().
My sqlite3_step holds for a 1s after read of last row data. Why?
-(NSDictionary*)specificationItemsForConfigurationsIds:(NSString*)configurationsIdsStr
{
[self databaseOpen];
NSString *query = [NSString stringWithFormat:#"SELECT SpecItem.id,SpecItem.name,ConfigurationSpec.configuration_id\
FROM (SpecItem INNER JOIN ConfigurationSpec ON ConfigurationSpec.spec_item_id=SpecItem.id)\
WHERE (SpecItem.parent_id=12 OR SpecItem.parent_id=34 OR SpecItem.id=23 OR SpecItem.id=27) AND ConfigurationSpec.configuration_id IN (%#)",configurationsIdsStr];
sqlite3_stmt *statement;
NSMutableDictionary* configurationsWithSpecItems = [NSMutableDictionary new];
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
int specItemId = sqlite3_column_int(statement, 0);
NSString* specItemName = [self sqlite3_column_text_asString_ofStatement:statement
atColumn:1];
int configId = sqlite3_column_int(statement, 2);
NSString* configIdNumber = [NSString stringWithFormat:#"%d",configId];
NSMutableArray* specItems = [configurationsWithSpecItems objectForKey:configIdNumber];
if(specItems == nil)
{
specItems = [NSMutableArray new];
[configurationsWithSpecItems setObject:specItems
forKey:configIdNumber];
}
SpecificationItem* specItem = [SpecificationItem specificationItemWithId:specItemId
name:specItemName];
[specItems addObject:specItem];
// When we read last row data, getting from here to POINT 2 takes 1s
}
// POINT 2
sqlite3_finalize(statement);
}
[self databaseClose];
return configurationsWithSpecItems;
}
Single read of one row takes 2-3ms, but after last one getting out of while loop takes 1s, which is too much for me.
EXPLAIN QUERY PLAN output for this query:
0 0 1 SCAN TABLE Configuration (~100000 rows)
0 0 0 EXECUTE LIST SUBQUERY 1
1 0 0 SEARCH TABLE Configuration USING AUTOMATIC COVERING INDEX (model_id=?) (~7 rows)
0 1 0 SEARCH TABLE SpecItem USING INTEGER PRIMARY KEY (rowid=?) (~1 rows)
There are two explanations for the delay; one or both might apply:
All the records that match are at the beginning of the Configuration table. After the last matching record, SQLite still has to search through all the remaining records, but none matches.
SQLite creates a temporary index on the model_id column because it estimates that the query would be even slower without it. After the query has finished, that index must be deleted again; what you see is the time needed to synchronize at the end of the (automatic) transaction.
Create an index on the model_id column will help avoiding both of these points.
If possible, you should try to merge the subquery (in configurationsIdStr) into the outer query; instead of:
... ConfigurationSpec.configuration_id IN (
SELECT configuration_id FROM Configuration WHERE model_id = 42)
use something like this:
... ConfigurationSpec.model_id = 42
Avoiding that indirection makes it much easier for SQLite to optimize the query execution.
I'm a noob when it comes to sqlite and not quite sure how to do this.
I want a database with a bunch of row, containing one word each. When the user types a word, I will validate it by checking if its in the database.
Things I dont have, I guess, and don't know how to create, is an index? How do I insert that? How do I write the query to take advantage of index?
I also have two columns in there, "id and word". Is it good to have the id or does it just take up space?
This is what I got so far:
CREATE TABLE words (id INTEGER PRIMARY KEY, word VARCHAR(15));
I don't want words longer then 15 characters, so I set the VARCHAR(15);
INSERT INTO words(word) VALUES('hello');
INSERT INTO words(word) VALUES('bye');
etc. for all words
And to check a word:
NSString *sql = [NSString stringWithFormat:#"SELECT EXISTS(SELECT 1 FROM words WHERE word=\"%#\" LIMIT 1)", word];
const char *sqlStatement = [sql UTF8String];
if (sqlite3_prepare_v2(db, sqlStatement, -1, &selectStmt, NULL) == SQLITE_OK)
{
int count = 0;
while(sqlite3_step(selectStmt) == SQLITE_ROW)
{
count = sqlite3_column_int(selectStmt, 0);
}
NSLog(#"COUNT: %i",count);
//If count is 1, we have a match.
}
Yes. Your Statement is ok.
You can also use ' intead of ":
NSString *sql = [NSString stringWithFormat:#"SELECT EXISTS(SELECT 1 FROM words WHERE word='%#' LIMIT 1)", word];
Is it good to have the id or does it just take up space?
It depends on your need, I will suggest you should keep an Id field as primary key.
For creating index you can use:
CREATE INDEX yourIndexName ON yourTableName ( yourColumnName )
For more about indexing check sqlite