1.新建empty application项目,添加两个UIViewController视图:HomeViewController(主视图,搜索)、AddViewController(添加信息视图)。
注意:TextField要选择委托(delegate)
2.添加支持sqlite3的动态链接库:libsqlite3.dylib。
3.主要代码:
// HomeViewController.h
// SQLiteDemo
//
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#define kDatabaseName @"database.sqlite"
@interface HomeViewController : UIViewController<UITextFieldDelegate>
{
sqlite3 *database;
}
@property (retain, nonatomic) IBOutlet UITextField *idTextField;
@property (retain, nonatomic) IBOutlet UILabel *nameLabel;
- (void)createDatabase;
- (IBAction)searchAction:(id)sender;
- (IBAction)addAction:(id)sender;
// SQLiteDemo
//
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#define kDatabaseName @"database.sqlite"
@interface HomeViewController : UIViewController<UITextFieldDelegate>
{
sqlite3 *database;
}
@property (retain, nonatomic) IBOutlet UITextField *idTextField;
@property (retain, nonatomic) IBOutlet UILabel *nameLabel;
- (void)createDatabase;
- (IBAction)searchAction:(id)sender;
- (IBAction)addAction:(id)sender;
@end
// HomeViewController.m
// SQLiteDemo
//
#import "HomeViewController.h"
#import "AddViewController.h"
@interface HomeViewController ()
@end
@implementation HomeViewController
@synthesize idTextField;
@synthesize nameLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
[self createDatabase];
}
- (void)viewDidUnload
{
[self setIdTextField:nil];
[self setNameLabel:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)dealloc {
[idTextField release];
[nameLabel release];
[super dealloc];
}
- (void)createDatabase
{
//获取数据库文件路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *thePath = [paths objectAtIndex:0];
NSString *file = [thePath stringByAppendingPathComponent:kDatabaseName];
//创建数据库
if (sqlite3_open([file UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert(0, @"未能打开数据库");
}
//创建表
char *errmsg;
NSString *createTableSQL = @"CREATE TABLE IF NOT EXISTS STUDENT(ID INTEGER PRIMARY KEY, NAME TEXT);";
if (sqlite3_exec(database, [createTableSQL UTF8String], nil, nil, &errmsg) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert1(0, @"未能创建表:%s", errmsg);
sqlite3_free(errmsg);
}
}
- (IBAction)searchAction:(id)sender
{
[idTextField resignFirstResponder];
BOOL notFound = YES;
NSString *selectSQL = [[NSString alloc] initWithFormat:@"SELECT ID, NAME FROM STUDENT WHERE ID = %@", idTextField.text];
sqlite3_stmt *statement;
if (sqlite3_prepare(database, [selectSQL UTF8String], -1, &statement, nil) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
notFound = NO;
char *name = (char *)sqlite3_column_text(statement, 1);
nameLabel.text = [NSString stringWithFormat:@"%s", name];
}
}
sqlite3_finalize(statement);
if (notFound)
{
nameLabel.text = @"没有记录";
}
[selectSQL release];
}
- (IBAction)addAction:(id)sender
{
AddViewController *addViewController = [[AddViewController alloc] init];
[self presentModalViewController:addViewController animated:YES];
[addViewController release];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
// SQLiteDemo
//
#import "HomeViewController.h"
#import "AddViewController.h"
@interface HomeViewController ()
@end
@implementation HomeViewController
@synthesize idTextField;
@synthesize nameLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
[self createDatabase];
}
- (void)viewDidUnload
{
[self setIdTextField:nil];
[self setNameLabel:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)dealloc {
[idTextField release];
[nameLabel release];
[super dealloc];
}
- (void)createDatabase
{
//获取数据库文件路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *thePath = [paths objectAtIndex:0];
NSString *file = [thePath stringByAppendingPathComponent:kDatabaseName];
//创建数据库
if (sqlite3_open([file UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert(0, @"未能打开数据库");
}
//创建表
char *errmsg;
NSString *createTableSQL = @"CREATE TABLE IF NOT EXISTS STUDENT(ID INTEGER PRIMARY KEY, NAME TEXT);";
if (sqlite3_exec(database, [createTableSQL UTF8String], nil, nil, &errmsg) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert1(0, @"未能创建表:%s", errmsg);
sqlite3_free(errmsg);
}
}
- (IBAction)searchAction:(id)sender
{
[idTextField resignFirstResponder];
BOOL notFound = YES;
NSString *selectSQL = [[NSString alloc] initWithFormat:@"SELECT ID, NAME FROM STUDENT WHERE ID = %@", idTextField.text];
sqlite3_stmt *statement;
if (sqlite3_prepare(database, [selectSQL UTF8String], -1, &statement, nil) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
notFound = NO;
char *name = (char *)sqlite3_column_text(statement, 1);
nameLabel.text = [NSString stringWithFormat:@"%s", name];
}
}
sqlite3_finalize(statement);
if (notFound)
{
nameLabel.text = @"没有记录";
}
[selectSQL release];
}
- (IBAction)addAction:(id)sender
{
AddViewController *addViewController = [[AddViewController alloc] init];
[self presentModalViewController:addViewController animated:YES];
[addViewController release];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
@end
在类的实现中,createDatabase方法,完成数据库文件和Student表的创建。
// AddViewController.h
// SQLiteDemo
//
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#define kDatabaseName @"database.sqlite"
@interface AddViewController : UIViewController<UITextFieldDelegate>
{
sqlite3 *database;
}
@property (retain, nonatomic) IBOutlet UITextField *idTextField;
@property (retain, nonatomic) IBOutlet UITextField *nameTextField;
@property (retain, nonatomic) IBOutlet UIButton *saveButton;
@property (retain, nonatomic) IBOutlet UIButton *cancelButton;
- (void)saveInfoIntoDatabase;
- (BOOL)checkInfo;
- (IBAction)saveAction:(id)sender;
- (IBAction)cancelAction:(id)sender;
//
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#define kDatabaseName @"database.sqlite"
@interface AddViewController : UIViewController<UITextFieldDelegate>
{
sqlite3 *database;
}
@property (retain, nonatomic) IBOutlet UITextField *idTextField;
@property (retain, nonatomic) IBOutlet UITextField *nameTextField;
@property (retain, nonatomic) IBOutlet UIButton *saveButton;
@property (retain, nonatomic) IBOutlet UIButton *cancelButton;
- (void)saveInfoIntoDatabase;
- (BOOL)checkInfo;
- (IBAction)saveAction:(id)sender;
- (IBAction)cancelAction:(id)sender;
@end
// AddViewController.m
// SQLiteDemo
//
#import "AddViewController.h"
@interface AddViewController ()
@end
@implementation AddViewController
@synthesize idTextField;
@synthesize nameTextField;
@synthesize saveButton;
@synthesize cancelButton;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[self setIdTextField:nil];
[self setNameTextField:nil];
[self setSaveButton:nil];
[self setCancelButton:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)dealloc {
[idTextField release];
[nameTextField release];
[saveButton release];
[cancelButton release];
[super dealloc];
}
- (void)saveInfoIntoDatabase
{
//打开数据库,获得数据库文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *thePath = [paths objectAtIndex:0];
NSString *file = [thePath stringByAppendingPathComponent:kDatabaseName];
if (sqlite3_open([file UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert(0, @"未能打开数据库");
}
NSString *insertSQL = [[NSString alloc] initWithFormat:@"INSERT OR REPLACE INTO STUDENT(ID, NAME) VALUES(%@, '%@');", idTextField.text, nameTextField.text];
char *errmsg;
if (sqlite3_exec(database, [insertSQL UTF8String], nil, nil, &errmsg) != SQLITE_OK)
{
NSAssert1(0, @"未能插入值:%s", errmsg);
sqlite3_free(errmsg);
}
[insertSQL release];
sqlite3_close(database);
}
- (BOOL)checkInfo
{
if ([idTextField.text isEqual:@""] || [nameTextField.text isEqualToString:@""])
{
return NO;
}
return YES;
}
- (IBAction)saveAction:(id)sender
{
NSLog(@"检查信息:%d", [self checkInfo]);
//保存
if (![self checkInfo])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"请输入信息" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
//将信息保存到数据库
[self saveInfoIntoDatabase];
[self dismissModalViewControllerAnimated:YES];
}
}
- (IBAction)cancelAction:(id)sender
{
//取消,重置
[idTextField setText:@""];
[nameTextField setText:@""];
[idTextField resignFirstResponder];
[nameTextField resignFirstResponder];
[self dismissModalViewControllerAnimated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == idTextField)
{
[textField resignFirstResponder];
[nameTextField becomeFirstResponder];
}
else
{
[textField resignFirstResponder];
}
return YES;
}
@end
//
#import "AddViewController.h"
@interface AddViewController ()
@end
@implementation AddViewController
@synthesize idTextField;
@synthesize nameTextField;
@synthesize saveButton;
@synthesize cancelButton;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[self setIdTextField:nil];
[self setNameTextField:nil];
[self setSaveButton:nil];
[self setCancelButton:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)dealloc {
[idTextField release];
[nameTextField release];
[saveButton release];
[cancelButton release];
[super dealloc];
}
- (void)saveInfoIntoDatabase
{
//打开数据库,获得数据库文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *thePath = [paths objectAtIndex:0];
NSString *file = [thePath stringByAppendingPathComponent:kDatabaseName];
if (sqlite3_open([file UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert(0, @"未能打开数据库");
}
NSString *insertSQL = [[NSString alloc] initWithFormat:@"INSERT OR REPLACE INTO STUDENT(ID, NAME) VALUES(%@, '%@');", idTextField.text, nameTextField.text];
char *errmsg;
if (sqlite3_exec(database, [insertSQL UTF8String], nil, nil, &errmsg) != SQLITE_OK)
{
NSAssert1(0, @"未能插入值:%s", errmsg);
sqlite3_free(errmsg);
}
[insertSQL release];
sqlite3_close(database);
}
- (BOOL)checkInfo
{
if ([idTextField.text isEqual:@""] || [nameTextField.text isEqualToString:@""])
{
return NO;
}
return YES;
}
- (IBAction)saveAction:(id)sender
{
NSLog(@"检查信息:%d", [self checkInfo]);
//保存
if (![self checkInfo])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"请输入信息" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
//将信息保存到数据库
[self saveInfoIntoDatabase];
[self dismissModalViewControllerAnimated:YES];
}
}
- (IBAction)cancelAction:(id)sender
{
//取消,重置
[idTextField setText:@""];
[nameTextField setText:@""];
[idTextField resignFirstResponder];
[nameTextField resignFirstResponder];
[self dismissModalViewControllerAnimated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == idTextField)
{
[textField resignFirstResponder];
[nameTextField becomeFirstResponder];
}
else
{
[textField resignFirstResponder];
}
return YES;
}
@end