【问题标题】:Can not add data to sqlite in objective c ios无法在objective c ios中将数据添加到sqlite
【发布时间】:2018-08-31 19:30:47
【问题描述】:

我正在尝试将数据添加到SQLite 数据库。数据是从json 文件中以NSDictionary 获取的,我正在尝试将该数据从NSDictionary 插入到SQLite,但我很困惑如何继续。

我在控制台中获取值,但它显示在控制台中 Failed to create table

这是我到目前为止所做的:

在我的 ViewController.h 中:

#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>
#import <sqlite3.h>

@interface ViewController : UIViewController

@property (strong, nonatomic) NSString * dbPath;
@property (nonatomic) sqlite3 *DB;
@property (strong, nonatomic) NSString * sunrisev;
@property (strong, nonatomic) NSString * sunsetv;
@property (strong, nonatomic) NSString * midnightv;

@end

这里是 ViewController.m 类:

#import "ViewController.h"
#import "SQLiteManager.h"

@interface ViewController () {
NSUserDefaults *defaults;
}

@end

bool isGrantedNotificationAccess;

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];


NSURL *url = [NSURL fileURLWithPath:@"/Users/macbook/Desktop/Test/Test/AdhanTimeFor_1_25_67_2_2018.json"];
NSString *fileContent = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"Json data is here %@", fileContent);
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"myJsonFile" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

NSArray *dataDic = json[@"data"];
NSLog(@"this is whole data dic %@", dataDic);
NSArray *dataArr = json[@"data"];
[dataArr enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
    NSDictionary *timings = object[@"timings"];

    _sunrisev = timings[@"Sunrise"];
    _sunsetv = timings[@"Sunset"];
    _midnightv = timings[@"Midnight"];

    NSLog(@"sun rise array is %@", _sunrisev);
    NSLog(@"sunset array is %@", _sunsetv);
    NSLog(@"midnight array is %@", _midnightv);
}];

NSString *docsDir;
NSArray *dirPaths;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, TRUE);
docsDir = dirPaths[0];

_dbPath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"MyDatabase.db"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:_dbPath] == NO) {
    const char *dbPathagain = [_dbPath UTF8String];

    if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {
         char *errorMessage;
         const char *sql_statement = "CREATE TABLE IF NOT EXISTS jsontable(ID integer primary key, sunrise text, sunset text, midnight text)";
        NSLog(@"created table success");

        sqlite3_stmt *statement;
        const char *dbPathagain = [ _dbPath UTF8String];

        if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {
            NSString *insertSQLData = [NSString stringWithFormat:@"INSERT INTO jsontable( sunrise, sunset, midnight) VALUES (\"%@\", \"%@\", \"%@\")", _sunsetv,  _sunsetv, _midnightv];
            const char *insert_statement = [insertSQLData UTF8String];
            sqlite3_prepare_v2(_DB, insert_statement, -1, &statement, NULL);

            if (sqlite3_step(statement) == SQLITE_DONE) {
                NSLog(@"data added successfully");
                NSLog(@"here is sunrise times %@", _sunrisev);
            }
            else {
                NSLog(@"could not add timings");
            }
            sqlite3_finalize(statement);
            sqlite3_close(_DB);
        }

        if (sqlite3_exec(_DB, sql_statement, NULL, NULL, &errorMessage) != SQLITE_OK) {
            NSLog(@"failed to create table");
        }
        sqlite3_close(_DB);
    }
    else {
        NSLog(@"fAILED to open db or cretate table");
    }
}
}

【问题讨论】:

  • 在下一行工作,这是无效的。 NSString *insertSQLData = [NSString stringWithFormat:@"INSERT INTO jsontable( 日出、日落、午夜) VALUES (\"%@\", \"%@\", \"%@\")"
  • 你能帮我回答一下吗
  • 不要在您的 iOS 应用中将文件路径硬编码到您的计算机。
  • 错字:NSDocumentationDirectory 应该是 NSDocumentDirectory

标签: ios objective-c sqlite nsarray nsdictionary


【解决方案1】:

试试这个代码来创建你的表: 添加这两个属性:

@property (strong, nonatomic) NSString *databasePath;
@property (nonatomic) sqlite3 *myDataBase;

- (void)createDatabase
{
    // get the path to our data base
    NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *doctumentsDirectory = [directories lastObject];
    self.databasePath = [[NSString alloc] initWithString:[doctumentsDirectory stringByAppendingPathComponent:@"MyDatabase.db"]];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    // create DB if it does not already exists
    if (![fileManager fileExistsAtPath:self.databasePath]) {

        const char *dbPath = [self.databasePath UTF8String];

        if (sqlite3_open(dbPath, &_myDataBase) == SQLITE_OK) {

            char *errorMsg;
            const char *sql_statement = "CREATE TABLE IF NOT EXISTS jsontable (ID INTEGER PRIMARY KEY AUTOINCREMENT, sunrise TEXT, sunset TEXT, midnight TEXT)";

            if (sqlite3_exec(_myDataBase, sql_statement, NULL, NULL, &errorMsg) != SQLITE_OK) {

                [self errorCreatingTable:[NSString stringWithFormat:@"failed creating table. ERROR:%s", errorMsg]];
            }

            sqlite3_close(_myDataBase);

        } else {
           // error creating table

        }
    }
}

【讨论】:

  • 错误:在“ViewController *”类型的对象上找不到属性“databasePath”
  • 是,但仍然没有创建表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 2011-07-01
相关资源
最近更新 更多