아이폰어플개발정보2010. 10. 12. 04:04
복잡한 SQLite3 간단하게 하는 클래스
This library is more suitable for smaller databases as right now is automatically transforming all the data from select into the NSMutableArray where every row has it's Own NSMutableDictionary. This is not the best idea if you have loads of data, because that you have all the data in the variable and that means that it eats all your memory and application crashes.

To get some data from database is as easy as that:

  1. NSMutableArray *arr = [conn getData:@"SELECT * FROM testTable;" fromDatabase:@"testDatabase"];  

http://code.google.com/p/sqlite3connector/

Now I'll show you how easy is to connect to the database and retrieve some data.

  1. //
  2. //  ContactsController.h
  3. //  TestApp
  4. //
  5. //  Created by Ondrej Rafaj on 26.10.09.
  6. //  Copyright 2009 Home. All rights reserved.
  7. //
  8. #import 
  9. #import "SQLite3Connector.h"
  10. @interface ContactsController : UIViewController {  
  11.     IBOutlet UITableView *table;  
  12.     IBOutlet UIActivityIndicatorView *preloader;  
  13.     NSMutableArray *data;  
  14.     SQLite3Connector *conn;  
  15. }  
  16. @property (nonatomic, retain) IBOutlet UITableView *table;  
  17. @property (nonatomic, retain) IBOutlet UIActivityIndicatorView *preloader;  
  18. @property (nonatomic, retain) NSMutableArray *data;  
  19. @end  

We've included the SQLite3Connector class into the project and we've created tableView and activity indicator as a preloader, than we have the data variable where we are going to have all the results from the database. Last thing is a class SQLite3Connector which allows you to do all the queries.

  1. //
  2. //  ContactsController.m
  3. //  TestApp
  4. //
  5. //  Created by Ondrej Rafaj on 26.10.09.
  6. //  Copyright 2009 Home. All rights reserved.
  7. //
  8. #import "ContactsController.h"
  9. @implementation ContactsController  
  10. @synthesize table, preloader, data;  
  11. /* 
  12. - (id)initWithStyle:(UITableViewStyle)style { 
  13.     // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. 
  14.     if (self = [super initWithStyle:style]) { 
  15.     } 
  16.     return self; 
  17. } 
  18. */
  19. - (void) importDataFromContacts {  
  20.     // creating fake data for import
  21.     [conn executeQuery:@"INSERT INTO contacts (name, surname) VALUES ('Ondrej', 'Rafaj');" inDatabase:@"contacts"];  
  22.     [conn executeQuery:@"INSERT INTO contacts (name, surname) VALUES ('Hana', 'Cerna');" inDatabase:@"contacts"];  
  23.     [conn executeQuery:@"INSERT INTO contacts (name, surname) VALUES ('Andrew', 'Walker');" inDatabase:@"contacts"];  
  24.     [conn executeQuery:@"INSERT INTO contacts (name, surname) VALUES ('Greg', 'Jarrett');" inDatabase:@"contacts"];  
  25.     [conn executeQuery:@"INSERT INTO contacts (name, surname) VALUES ('Chris', 'Doull');" inDatabase:@"contacts"];  
  26.     [conn executeQuery:@"INSERT INTO contacts (name, surname) VALUES ('Malc', 'Seaborn');" inDatabase:@"contacts"];  
  27.     [conn executeQuery:@"INSERT INTO contacts (name, surname) VALUES ('Jidh', 'George');" inDatabase:@"contacts"];  
  28. }  
  29. - (void)viewDidLoad {  
  30.     [super viewDidLoad];  
  31.     [preloader startAnimating];  
  32.     conn = [[SQLite3Connector alloc] init];  
  33.     if ([SQLite3Connector databaseExists:@"contacts"]) [SQLite3Connector dropDatabase:@"contacts"];  
  34.     NSString *query = @"";  
  35.     query = @"CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, surname VARCHAR);";  
  36.     if (![conn executeQuery:query inDatabase:@"contacts"]) NSAssert1(0, @"Error creating database. (%@)", query);  
  37.     [self importDataFromContacts];  
  38.     NSLog(@"Creating database & importing contacts");  
  39.     data = [conn getData:@"SELECT * FROM contacts ORDER BY surname ASC;" fromDatabase:@"contacts"];  
  40.     [table reloadData];  
  41.     [preloader stopAnimating];  
  42. }  
  43. - (void)didReceiveMemoryWarning {  
  44.     // Releases the view if it doesn't have a superview.
  45.     [super didReceiveMemoryWarning];  
  46.     // Release any cached data, images, etc that aren't in use.
  47. }  
  48. - (void)viewDidUnload {  
  49.     // Release any retained subviews of the main view.
  50.     // e.g. self.myOutlet = nil;
  51. }  
  52. #pragma mark Table view methods
  53. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {  
  54.     return 1;  
  55. }  
  56. // Customize the number of rows in the table view.
  57. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {  
  58.     return [data count];  
  59. }  
  60. // Customize the appearance of table view cells.
  61. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  
  62.     static NSString *CellIdentifier = @"Cell";  
  63.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
  64.     if (cell == nil) {  
  65.         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];  
  66.     }  
  67.     int index = [indexPath indexAtPosition: [indexPath length] - 1];  
  68.     cell.textLabel.text = [NSString stringWithFormat:@"%@, %@", [[data objectAtIndex: index] objectForKey: @"surname"], [[data objectAtIndex: index] objectForKey: @"name"]];  
  69.     return cell;  
  70. }  
  71. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {  
  72.     // Navigation logic may go here. Create and push another view controller.
  73.     // AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
  74.     // [self.navigationController pushViewController:anotherViewController];
  75.     // [anotherViewController release];
  76. }  
  77. - (void)dealloc {  
  78.     [table, preloader, data release];  
  79.     [super dealloc];  
  80. }  
  81. @end  

Check out the importDataFromContacts and viewDidLoad functions ... here you can see that the handling SQLite is quite piece of cake.

All the source codes are available on the google code here:

Here is a little bit more extended example of what you can do with it, please don't worry about the printResults function, I just took part of the example project as I don't have a time right now to prepare anything better (I want to go home, I'm still stucked in the office and right now is 21:45), ok here we go:

  1. - (void) printResults:(NSString *)text {  
  2.     counter++;  
  3.     textView.text = [NSString stringWithFormat:@"%d) %@\r\n\r\n%@", counter, text, textView.text];  
  4. }  
  5. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
  6. - (void)viewDidLoad {  
  7.     [super viewDidLoad];  
  8.     counter = 0;  
  9.     SQLite3Connector *conn = [[SQLite3Connector alloc] init];  
  10.     //[conn getData:@"" fromDatabase:@""];
  11.     NSString *queryCount = @"SELECT COUNT(id) FROM testTable;";  
  12.     [self printResults:[NSString stringWithFormat:@"Directory path: %@", [SQLite3Connector getDocumentsDirectoryPath]]];  
  13.     [self printResults:[NSString stringWithFormat:@"Database folder path: %@", [SQLite3Connector getDatabaseFolderPath]]];  
  14.     [self printResults:[NSString stringWithFormat:@"Database file name: %@", [SQLite3Connector getDatabasePathFromName:@"testDatabase"]]];  
  15.     [self printResults:[NSString stringWithFormat:@"Escape string (it's): %@", [SQLite3Connector escapeString:@"it's"]]];  
  16.     //[self printResults:[NSString stringWithFormat:@"Dropping database: %d", [SQLite3Connector dropDatabase:@"testDatabase"]]];
  17.     [self printResults:[NSString stringWithFormat:@"Database exists: %d", [SQLite3Connector databaseExists:@"testDatabase"]]];  
  18.     NSString *query = @"CREATE TABLE IF NOT EXISTS testTable (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT);";  
  19.     [self printResults:[NSString stringWithFormat:@"Creating table: %d", [conn executeQuery:query inDatabase:@"testDatabase"]]];  
  20.     [self printResults:[NSString stringWithFormat:@"Database size: %@", [SQLite3Connector getDatabaseFormatedFileSize:@"testDatabase"]]];  
  21.     //[self printResults:[NSString stringWithFormat:@"Dropping table: %d", [conn dropTable:@"testTable" inDatabase:@"testDatabase" useVacuum:YES]]];
  22.     //[self printResults:[NSString stringWithFormat:@"Creating table: %d", [conn executeQuery:query inDatabase:@"testDatabase"]]];
  23.     //[self printResults:[NSString stringWithFormat:@"Database size: %@", [SQLite3Connector getDatabaseFormatedFileSize:@"testDatabase"]]];
  24.     //[self printResults:[NSString stringWithFormat:@"Database exists: %d", [SQLite3Connector databaseExists:@"testDatabase"]]];
  25.     query = @"INSERT INTO testTable (data) VALUES ('Test Data (It''s)');";  
  26.     [self printResults:[NSString stringWithFormat:@"Inserting into the table: %d", [conn executeQuery:query inDatabase:@"testDatabase"]]];  
  27.     //[self printResults:[NSString stringWithFormat:@"Truncate table: %@", [conn truncateTable:@"testTable" inDatabase:@"testDatabase"]]];
  28.     [self printResults:[NSString stringWithFormat:@"Inserting into the table: %d", [conn executeQuery:query inDatabase:@"testDatabase"]]];  
  29.     [self printResults:[NSString stringWithFormat:@"Database size: %@", [SQLite3Connector getDatabaseFormatedFileSize:@"testDatabase"]]];  
  30.     [self printResults:[NSString stringWithFormat:@"Inserting into the table: %d", [conn executeQuery:query inDatabase:@"testDatabase"]]];  
  31.     [self printResults:[NSString stringWithFormat:@"Table exists: %d", [conn tableExists:@"testTable" inDatabase:@"testDatabase"]]];  
  32.     [self printResults:[NSString stringWithFormat:@"Database size: %@", [SQLite3Connector getDatabaseFormatedFileSize:@"testDatabase"]]];  
  33.     [self printResults:[NSString stringWithFormat:@"Table exists: %d", [conn tableExists:@"testTable" inDatabase:@"testDatabase"]]];  
  34.     [self printResults:[NSString stringWithFormat:@"Count rows in the table: %d", [conn executeScalar:queryCount inDatabase:@"testDatabase"]]];  
  35.     NSMutableArray *arr = [conn getData:@"SELECT * FROM testTable;" fromDatabase:@"testDatabase"];  
  36.     NSLog(@"%@", arr);  
  37.     [conn release];  
  38. }  
  39. http://www.xprogress.com/post-38-new-sqlite3-handling-library-for-iphones-and-cocoa-now-under-development/
Posted by 오늘마감

댓글을 달아 주세요