How to view the content of .db file? - ios

I am using Xcode 6.4, developing apps for iOS 8 that need to use database. I inserted some information into my database ("something.db" file). I want to see the content of "something.db" to see what I inserted. How can I view its content?
This is my code for creating the database "company.db" and table "Staff"(ID PK, NAME TEXT, AGE INTEGER):
-(void) createOrOpenDB {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
dbPathString = [docPath stringByAppendingPathComponent:#"company.db"];
char *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:dbPathString]) {
const char *dbPath =[dbPathString UTF8String];
if(sqlite3_open(dbPath, &personDB)==SQLITE_OK) {
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS Staff (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE INTEGER)";
sqlite3_exec(personDB, sql_stmt, NULL, NULL, &error);
sqlite3_close(personDB);
}
}
}
This is my code for inserting information into the table "Staff":
- (IBAction)addPersonButton:(id)sender {
char *error;
if(sqlite3_open([dbPathString UTF8String], &personDB) == SQLITE_OK) {
NSString *insertStmt = [NSString stringWithFormat:#"INSERT INTO Staff (NAME, AGE) values ('%s', '%d')", [self.nameField.text UTF8String], [self.ageField.text intValue]];
const char *insert_stmt = [insertStmt UTF8String];
if(sqlite3_exec(personDB, insert_stmt, NULL, NULL, &error) == SQLITE_OK) {
NSLog(#"Person added");
Person *person = [[Person alloc] init];
[person setName:self.nameField.text];
[person setAge:[self.ageField.text intValue]];
[arrayofPerson addObject:person];
}
sqlite3_close(personDB);
}
}
The code works well because I was able to display the information of the "Staff" table in the tableview. But how to view that information in the .db file?
p/s: I changed it to "something.xls" but Excel does not display human readable information. I also downloaded Fileviewpro but did not know how to use. Someone helps me please!
Thank you very much!

You can use any app that is designed to view the contents of an sqlite file. for example: http://sqlitebrowser.org
If you are running on simulator you can use ~/Library/Developer/CoreSimulator/Devices/1A8DF360-B0A6-4815-95F3-68A6AB0BCC78/data/Container/Data/Application/
to get to the simulator just replace the long UDID with your device.

Related

Can not read data from the sqlite in iOS

I checked from sqlitebrowser that I successfully created sqlite and inserted data to sqlite, but now my problem is I could not read data from sqlite. I am new to sqlite.
Should I open the sqlite first, and read it? Where is wrong on my code below?
This code for open the existing sqlite.
-(void)openSqlite{
NSString *docsDir = [NSString stringWithFormat:#"Questiondata.db"];
NSArray *dirPaths;
_databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"Questiondata.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:_databasePath] == NO) {
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK) {
char *errorMessage;
const char *sql_statement ="CREATE TABLE IF NOT EXISTS users (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
if (sqlite3_exec(_contactDB,sql_statement,NULL,NULL,&errorMessage) != SQLITE_OK) {
NSLog(#"Failed to create the table");
}
sqlite3_close(_contactDB);
}
else{
NSLog(#"Fail to open/create the table");
}
}
}
This is code for read data from existing sqlite.
-(void)readData{
NSLog(#"we came here");
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB)) {
NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM Questions WHERE QuestionNumber = 1"];
const char*query_statement = [querySQL UTF8String];
if (sqlite3_prepare_v2(_contactDB, query_statement, -1, &statement, NULL)== SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_ROW) {
NSString *addressfield = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement,0)];
NSLog(#"finddata:%#",addressfield);
}else{
NSLog(#"notfinddatabase");
}
sqlite3_finalize(statement);
}else{
NSLog(#"failed to serache database");
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
NSLog(#"not be here");
}
}
In openSqlite method
const char *sql_statement ="CREATE TABLE IF NOT EXISTS users (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
and in your query
NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM Questions WHERE QuestionNumber = 1"];
table name and column name are not same.
Change in Place "Questions" with "users" .
and also change "QuestionNumber" with the table column.
May be, it will helps you or feel free.
sqlite doesn't report all errors until you start accessing the data. For example just about any filename and path will pass without errors.
First of all you must check that, the database is in the Documents folder?
It's not there by default.
Perhaps it's in the main bundle?
Try this:
NSString *dbName = [[NSBundle mainBundle] pathForResource:#"dbFile" ofType:#"db"];

Issues when reading from a database in an iPhone app

I am making an iPhone app for a school project that reads and writes to a database. I have managed to get my code to write to it but it won't read. Below is the code I'm using to read:
NSString * paths=[self getWritableDBPath];
const char *dbpath = [paths UTF8String];
sqlite3_stmt *statement;
static sqlite3 *database = nil;
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT questionright, totalquestions, FROM results", nil];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
//code...
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
Here is getWritableDBPath:
-(NSString *) getWritableDBPath {
NSString *myDB = #"appData.db";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:myDB];
}
The reason it doesn't work is that the sqlite3_prepare_v2 if statement is never satisfied.
When I write to the database I copy it to documents.
I am quite sure the results table exists as I am able to write to it. Here is the original sql statement:
DROP TABLE IF EXISTS "Questions";
CREATE TABLE "Questions" ("QuestionID" INTEGER PRIMARY KEY NOT NULL , "Question" TEXT, "RightAnswer" TEXT, "WrongAnswer1" TEXT, "WrongAnswer2" TEXT, "Done" BOOL, "Catagory" TEXT, "Audio" INTEGER);
DROP TABLE IF EXISTS "Results";
CREATE TABLE "Results" ("ResultID" INTEGER PRIMARY KEY NOT NULL , "QuestionRight" INTEGER, "TotalQuestions" INTEGER, "Catagory" TEXT);
I did find a similar question on here but didn't think the answers were that relevant to me.
Thanks for your help.
If you want my advice, don't use the sqlite c libraries directly if you don't really need that, you can use FMDB library and get rid of all the c headache
https://github.com/ccgus/fmdb
You can simply do it like this
FMDatabase *db = [FMDatabase databaseWithPath:#"your full db path in documents goes here"];
if (![db open]) {
return;
}
FMResultSet *s = [db executeQuery:#"Your query goes here"];
if ([s next]) {
int totalCount = [s intForColumn:#"totalCount"];
}

unable to update or insert a row in a table

I want to update a row in my iPhone app. Below is the code. It shows in my log that query is executed and row has been updated, but when I excess that table, it seems to be empty. And also it always updates a row even if I am trying to enter a row with new id, it should insert instead of updating in this case.
//create local database
NSString *docsDir = NULL;
NSArray *dirPaths = NULL;
sqlite3 *localDB = NULL;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"localscentsy1.db"]];
NSLog(#"%#",databasePath);
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement = NULL;
if (sqlite3_open(dbpath, &localDB) == SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat:#"UPDATE Ratings set rating = '%d' WHERE perfume_id = ?",
(int)rating];
const char *update_stmt = [updateSQL UTF8String];
if(sqlite3_prepare_v2(localDB, update_stmt, -1, &statement, NULL ) ==SQLITE_OK){
sqlite3_bind_int(statement, 1, tappedItem.perfumeId);
}
char* errmsg;
sqlite3_exec(localDB, "COMMIT", NULL, NULL, &errmsg);
if(SQLITE_DONE != sqlite3_step(statement)){
NSLog(#"Error while updating. %s", sqlite3_errmsg(localDB));
NSLog(#"query failed: %s", sqlite3_errmsg(localDB));
NSLog(#"%#",#"update unsuccessfull");
NSLog(#"New data, Insert Please");
sqlite3_stmt *statement2 = NULL;
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO Ratings (perfume_id,rating) VALUES (\"%d\",\"%d\")",
tappedItem.perfumeId,
(int)rating];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(localDB, insert_stmt, -1, &statement2, NULL);
if (sqlite3_step(statement2) == SQLITE_DONE)
{
NSLog(#"New data, Inserted");
}
sqlite3_finalize(statement2);
}
else{
NSLog(#"%#",#"update successfull");
sqlite3_finalize(statement);
}
sqlite3_close(localDB);
}
Any help will be appreciated. I am new at ios development and this code is taking so much of my time. Here is my log which always says "update successful"
CyberGenies/Library/Application Support/iPhone Simulator/7.0/Applications/24D2FEE2- DBE6-441A-AC79-1F2D57F96C88/Documents/localscentsy1.db
2014-07-27 01:03:26.612 Scentsy Squirrel[19008:a0b] update successfull
Have you seen if the db really has the structure? Some times when you start doing queries in an empty db (I mean not even tables) the query itself build the structure you are giving it on the query. You can check by compiling on the simulator and look for the db in the Mac finder.

Sqlite3 database is not executing a query

I am developing an iPhone app in Xcode, I am unable to access the database I have created. Following is the code where I am creating my database
//create local database
NSString *docsDir;
NSArray *dirPaths;
sqlite3 *localDB;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"local.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO) {
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &localDB) == SQLITE_OK) {
char *errMsg;
const char *sql_stmt1 = "CREATE TABLE IF NOT EXISTS My_choices (perfume_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, na TEXT, got_it TEXT)";
const char *sql_stmt2 = "CREATE TABLE IF NOT EXISTS Ratings (perfume_id INTEGER PRIMARY KEY AUTOINCREMENT, rating NUMERIC)";
const char *sql_stmt3 = "CREATE TABLE IF NOT EXISTS Consultant_Details (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT,website TEXT,domain TEXT,domain_no NUMERIC,phone TEXT,facebook TEXT)";
if (sqlite3_exec(localDB, sql_stmt1, NULL, NULL, &errMsg) != SQLITE_OK) {
NSLog(#"%#",#"Failed to create table My_choices");
}
if (sqlite3_exec(localDB, sql_stmt2, NULL, NULL, &errMsg) != SQLITE_OK) {
NSLog(#"%#",#"Failed to create table ratings");
}
if (sqlite3_exec(localDB, sql_stmt3, NULL, NULL, &errMsg) != SQLITE_OK) {
NSLog(#"%#",#"Failed to create table Consultant_Details");
}
sqlite3_close(localDB);
}
else {
NSLog(#"%#",#"Failed to open/create database");
}
}
add below is the code where I am trying to access it
NSString *docsDir;
NSArray *dirPaths;
sqlite3 *localDB;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
NSString *dbPath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: #"local.db"]];
NSString *q = #"select * from Ratings where perfume_id in";
q = [q stringByAppendingString:idList];
NSLog(#"%#",q);
const char *sqlStatement2 = [q UTF8String];
sqlite3_stmt *compiledStatement2;
if(sqlite3_open([dbPath UTF8String], &localDB) == SQLITE_OK) {
if(sqlite3_prepare_v2(localDB, sqlStatement2, -1, &compiledStatement2, NULL) == SQLITE_OK) {
NSLog(#"%d", SQLITE_ROW);
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement2) == SQLITE_ROW) {
// Read the data from the result row
int r = sqlite3_column_int(compiledStatement2, 1);
int id = sqlite3_column_int(compiledStatement2, 0);
NSLog(#"%d", id);
for (ListItem *item in self.listItemArray) {
if(item.perfumeId == id){
item.rating = r;
}
}
}
}
else{
NSLog(#"query failed: %s", sqlite3_errmsg(localDB));
}
}
sqlite3_close(localDB);
I always get "query failed No such table exists:Ratings" in my log.
Any help will be appreciated.
Basically this error occured due to unavailabilty of Table in database or wrong query. According to your post, IT look like a error in query.
Query should be something like this:
NSString *q = #"select * from Ratings where perfume_id in ('12','13','14','15')";
Print your "String q" and make sure it follow as above.
Thanks everyone for your help.The database file with the same already existed at that path. So my first method where I was creating a database
if ([filemgr fileExistsAtPath: databasePath ] == NO) check was false and tables were not created.
first remove database file from document directory then use following code to create a sqlite table..
if (![fileManager fileExistsAtPath: _databasePath ])
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_myDataBase) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS My_choices (perfume_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, na TEXT, got_it TEXT);" //TEST
"CREATE TABLE IF NOT EXISTS Ratings (perfume_id INTEGER PRIMARY KEY AUTOINCREMENT, rating NUMERIC);" //USER
"CREATE TABLE IF NOT EXISTS Consultant_Details (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT,website TEXT,domain TEXT,domain_no NUMERIC,phone TEXT,facebook TEXT)"; //METADATA
if (sqlite3_exec(_myDataBase, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(#"Failed to create tables");
}
sqlite3_close(_myDataBase);
NSLog(#"DataBase created at: %#",_databasePath);
} else {
NSLog(#"Failed to open/create database");
}
}

sort SQL data in xcode

I am trying to sort / order SQL data in my iOS app. the database is working fine. i can add data, display in tableview, edit, delete everything is working fine. just can't sort. below is the code i am using.
-(void)sortTable
{
//CHECKING DIRECTORY AND CREATING DATABASE CODE STARTS
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths [0];
//Build the path to the database file
_databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"events.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath] == NO)
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_eventDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS EVENTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, EVENT TEXT, EVENTDATE TEXT)";
//closing database after creating
if (sqlite3_exec(_eventDB, sql_stmt, NULL, NULL, &errMsg) !=SQLITE_OK)
{
// sqlite3_close(_eventDB);
}
}
}
//CHECKING DIRECTORY AND CREATING DATABASE CODE ENDS
//sort sql table
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_eventDB) == SQLITE_OK)
{
NSString *sortSQLTable = [NSString stringWithFormat:#"SELECT EVENT FROM EVENTS ORDER BY EVENT"]; // EVENTS is the table name and EVENT is the column.
const char *sort_stmt = [sortSQLTable UTF8String];
sqlite3_prepare_v2(_eventDB, sort_stmt, -1, &statement, NULL);
}
}
I am executing this void statement in viewDidLoad.
I have searched a lot. tried different things. just could not make it work. can someone help please.
UPDATE:
I just found that the ORDER BY query is actually sorting the table, but its not saving the database.
any idea how i can save the database after sorting?
If you are looking to sort data to display on your tableview you could use a NSSortDescriptor.
Here is the documentation from Apple on how to use them.
The gist though is something like ..
//array of People objects with properties of firstName and lastName just for example
NSArray *firstNames = #[ #"Jan", #"Steve", #"Jay", #"Mike" ];
NSArray *lastNames = #[ #"Joker", #"Jones", #"Smith", #"Pham" ];
NSMutableArray *people = [NSMutableArray array];
[firstNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Person *person = [[Person alloc] init];
person.firstName = [firstNames objectAtIndex:idx];
person.lastName = [lastNames objectAtIndex:idx];
[people addObject:person];
}];
//make the descriptor
NSSortDescriptor *firstNameSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"firstName"
ascending:YES ];
//sort the array using the descriptor
NSLog(#"By first name: %#", [people sortedArrayUsingDescriptors:#[firstNameSortDescriptor]]);

Resources