为您的 iPhone 应用程序创建数据库有点冗长,但它有很多步骤,但非常简单:
首先,您应该下载 mozilla fire fox 并下载其附加组件,您可以通过单击工具选项找到 sqlite 数据库选项。您可以创建一个包含列和行的新数据库文件。创建数据库文件的过程很简单,之后您可以将该文件包含到您的 X 代码项目中。
例如:- 就像您通常包含在 Xcode 项目中的图像一样。
之后编写以下代码对我来说很好:)
在你的 . m文件写入如下sqlite代码
#import "YourHeaderFile"
static sqlite3 *database = nil;
static sqlite3_stmt *addStmt = nil;
static sqlite3_stmt *updateStmt = nil;
@implementation 'YourImplementClass'
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"YourDataBaseFileName.sqlite"];
}
- (void) insertValueToDatabase {
NSString *dbPath =[self getDBPath];
NSString *select_Meal = dummy_select_Meal;
NSString *dateTime = dummy_date_Time;
NSString *location = dummy_location;
NSString *mealItem = dummy_mealItem;
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sqlDB = "Insert into iHad(Mealtype,DateAndTime,Location,Mealitem) VALUES (?,?,?,?)";
if(sqlite3_prepare_v2(database, sqlDB, -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
sqlite3_bind_text(addStmt, 1, [select_Meal UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2, [dateTime UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 3, [location UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 4, [mealItem UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
//else
//SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid
//coffeeID = sqlite3_last_insert_rowid(database);
//Reset the add statement.
sqlite3_reset(addStmt);
}
else
sqlite3_close(database);
}
为了省钱,你可以创建一个这样的方法
-(void)saveButtonClick
{
if (![dummy_select_Meal length] || ![dummy_mealItem length])
{
UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:@"Select Meal Type/Meal Item"];
[alert setDelegate:self];
[alert addButtonWithTitle:@"Ok"];
[alert show];
[alert release];
}
else
{
indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(30,30,50,50)];
indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;//UIActivityIndicatorViewStyleWhiteLarge;//
[self insertValueToDatabase];-----------------------> To insert data into data base
iHadAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
[delegate readMealsFromDatabase];
[rootController reloadTable_SaveButton];
}
[rootController showTablePopupAction:nil];
}
如果您有任何问题,请回复我,我会帮助您:)