Я новичок в разработке iPhone. Я хочу вставить определенные данные в свою базу данных и получить ее и отобразить ее в таблице. Я создал Database data.sqlite
с таблицей «пользователь». Таблица имеет два значения: id (varchar) и имя (varchar). Я вставил 3 строки данных в таблицу через «insert into user value» («1», «xxxx»); в окне терминала. Я создал навигационную аппликацию под названием «testDb». В AppDelegate У меня есть два методаКак вставить данные в базу данных SQLite в iPhone
- (void)createEditableCopyOfDatabaseIfNeeded {
NSLog(@"Creating editable copy of database");
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"data.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"data.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
и
+(sqlite3 *) getNewDBConnection{
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.sqlite"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
NSLog(@"Database Successfully Opened :)");
}
else {
NSLog(@"Error in opening database :(");
}
return newDBconnection;
}
В RootViewController
-(void)initializeTableData{
sqlite3 *db=[DatabaseTestAppDelegate getNewDBConnection];
sqlite3_stmt *statement=nil;
const char *sql="select * from user";
if (sqlite3_prepare_v2(db, sql, -1, &statement, NULL)!=SQLITE_OK)
NSAssert1(0,@"error in preparing staement",sqlite3_errmsg(db));
else {
while(sqlite3_step(statement)==SQLITE_ROW)
[tableData addObject:[NSString stringWithFormat:@"%s",(char*)sqlite3_column_text(statement,1)]];
}
sqlite3_finalize(statement);
}
- (void)viewDidLoad {
[super viewDidLoad];
tableData=[[NSMutableArray alloc]init];
[self addMyObjectIntoDatabase];
[self initializeTableData];
[email protected]"Database test";
}
Чтобы отобразить содержимое
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSLog(@"before displaying data");
cell.textLabel.text=[tableData objectAtIndex:indexPath.row];
NSLog(@"after displaying data");
// Configure the cell.
return cell;
}
Это работает отлично, чтобы отобразить продолжение в таблице. Но теперь я хочу вставить еще одну строку в свою таблицу и отобразить вставленный контент вместе с предыдущим контентом. Поскольку я новичок в iPhone, я узнал из учебников, чтобы прочитать базу данных и отобразить ее содержимое. Как перейти к моей задаче вставки и отображения снова?
Используйте обертку для работы с SQLite вместо прямого использования API C. Это делает жизнь * настолько * намного проще ... http://cocoaheads.byu.edu/resources/sqlite –
Вот хороший учебник. нажмите [ЗДЕСЬ] (http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/) для ссылки. –