看著國外網(wǎng)站的教程,寫了一個小例子,一個聯(lián)系人的程序,包括 (姓名、地址、電話)三項內容,通過兩個按鈕,可以將信息保存或者查詢數(shù)據(jù)庫已有的信息。
UI就不說了,比較簡單。貼一下關鍵代碼,具體的話還是去看源代碼(正想辦法傳,我這git出點問題)。
?
/*根據(jù)路徑創(chuàng)建數(shù)據(jù)庫并創(chuàng)建一個表contact(id nametext addresstext phonetext)*/
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
?
NSString *docsDir;
NSArray *dirPaths;
?
// 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: @"contacts.db"]];
?
NSFileManager *filemgr = [NSFileManager defaultManager];
?
if ([filemgr fileExistsAtPath:databasePath] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB)==SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT,PHONE TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg)!=SQLITE_OK)
{
status.text = @"創(chuàng)建表失敗\n";
}
}
else
{
status.text = @"創(chuàng)建/打開數(shù)據(jù)庫失敗";
}
}
?
}
?
/*將數(shù)據(jù)保存只數(shù)據(jù)庫,當按下保存按鈕的時候*/
?
- (IBAction)SaveToDataBase:(id)sender
{
sqlite3_stmt *statement;
?
const char *dbpath = [databasePath UTF8String];
?
if (sqlite3_open(dbpath, &contactDB)==SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO CONTACTS (name,address,phone) VALUES(\"%@\",\"%@\",\"%@\")",name.text,address.text,phone.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement)==SQLITE_DONE) {
status.text = @"已存儲到數(shù)據(jù)庫";
name.text = @"";
address.text = @"";
phone.text = @"";
}
else
{
status.text = @"保存失敗";
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
?
/*根據(jù)輸入的姓名來查詢數(shù)據(jù)*/
- (IBAction)SearchFromDataBase:(id)sender
{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
?
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:@"SELECT address,phone from contacts where name=\"%@\"",name.text];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *addressField = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 0)];
address.text = addressField;
?
NSString *phoneField = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 1? ? )];
phone.text = phoneField;
?
status.text = @"已查到結果";
[addressField release];
[phoneField release];
}
else {
status.text = @"未查到結果";
address.text = @"";
phone.text = @"";
}
sqlite3_finalize(statement);
}
?
sqlite3_close(contactDB);
}
}