我正在尝试将字符串存储在 iOS 6 iPhone 应用程序的 SQLite 数据库中。这相当简单:当单击按钮时,一个笑话会显示在文本视图中。单击第二个按钮时,我想将该文本视图保存到 SQLite 数据库中(saveJoke)。但是,SQLITE_DONE 永远不会返回,表明这不起作用。所以,看看我的警报,当下面执行 saveJoke 时,我总是得到“失败”。
知道为什么这不起作用吗?我有一种感觉,我可能在创建和插入 SQLite 数据库时遗漏了一些基本的东西。非常感谢帮助!
我的代码:
JokeFirstViewController.m:
#import "JokeFirstViewController.h"
@interface JokeFirstViewController ()
@end
@implementation JokeFirstViewController
@synthesize joke = _joke;
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[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, JOKESAVED TEXT)"; //look into
sqlite3_close(_contactDB);
}
}
}
- (IBAction)saveJoke:(id)sender {
/* get current joke displayed */
self.joke = self.text.text;
NSString *currentJoke = self.joke;
NSString *jokeSaved = [[NSString alloc] initWithFormat:currentJoke];
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
@"INSERT INTO CONTACTS (jokesaved) VALUES (?)",
jokeSaved];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
void AlertWithMessage(NSString *message);
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Database" message:@"Success" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}
} else {
void AlertWithMessage(NSString *message);
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Database" message:@"Fail" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
}
JokeFirstViewController.h:
#import <UIKit/UIKit.h>
#import <MessageUI/MFMessageComposeViewController.h>
#import <sqlite3.h>
@interface JokeFirstViewController : UIViewController <MFMessageComposeViewControllerDelegate>
- (IBAction)saveJoke:(id)sender;
- (IBAction)shareJoke:(id)sender;
- (IBAction)generateJoke:(id)sender;
@property (strong, nonatomic) IBOutlet UITextView *text;
@property (copy, nonatomic) NSString *joke;
@property (strong, nonatomic) NSString *databasePath;
@property (nonatomic) sqlite3 *contactDB;
@end