sqlite3数据库建表如何建立一个日期型的数据?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlite3数据库建表如何建立一个日期型的数据?相关的知识,希望对你有一定的参考价值。

给一个SQL例句吧,插入的能提供最好了。如果我想把几个日期放在一个字段里面应该怎么存放呢?因为有几个日期是一类的,但个数不确定。

几个日期放在一个字段里,类型就不可能再是日期类型了,系统没有你那么聪明,你得把这个字段变成文本类型的,才可以存多个日期。 参考技术A 日期函数
datetime() : 产生日期和时间
date(): 产生日期
time():产生时间
strftime():对以上3个函数产生的日期和时间进行格式化
用法实例:
1、SELECT date('2011-9-9','+1 day','+1 year'); 结果是 2010-09-10
2、SELECT datetime('now'); 当前日期和时间
3、SELECT datetime('now', 'start of month'); 本月的第一天零点,也可以设置年和日的第一天
4、SELECT datetime('now','+1 hour','-12 minute'); 当前时间加48分钟
strftime()函数可以将YYYY-MM-DD HH:MM:SS格式的日期字符串转换为其它形式的字符串
%d:天数,01-31
%f :小数形式的秒,SS.SSS
%H:小时
%j :某一天是该年的第几天,001-366
%m:月份,00-12
%M:分钟,00-59
%s:从1970到现在的秒数
%S:秒,00-59
%w:星期,0-6,0是星期天
%W:某天是该年的第几周,01-53
%Y:年,YYYY
%% 百分号
应用举例:
SELECT strftime('%Y.%m.%d %H:%M:%S','now','localtime');

如何以编程方式在 sqlite 数据库中创建表

【中文标题】如何以编程方式在 sqlite 数据库中创建表【英文标题】:how to create table in sqlite data base programmatically 【发布时间】:2011-03-26 05:59:24 【问题描述】:

我是 iphone 上的 sqlite 新手。

我要使用终端创建一个数据库。现在我需要通过我的应用程序中的代码创建一个表。

我的代码是

-(BOOL)createtable:(NSString *)tableName 
    BOOL ret;
    int rc;
    // SQL to create new table

    NSString *sql_str = [NSString stringWithFormat:@"CREATE TABLE %@ (pk INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , ItemName VARCHAR(100), Quantity INTEGER DEFAULT 0, Status BOOLEAN,Type VARCHAR(100))", tableName];

    const char *sqlStatement = (char *)[sql_str UTF8String];
    NSLog(@"query %s",sqlStatement);

    sqlite3_stmt *stmt;
    rc = sqlite3_prepare_v2(database, sqlStatement, -1, &stmt, NULL);

    ret = (rc == SQLITE_OK);
    if (ret)
     // statement built, execute
        rc = sqlite3_step(stmt);
        ret = (rc == SQLITE_DONE);
    

    sqlite3_finalize(stmt); // free statement
    NSLog(@"creating table");
    return ret;

但是没有创建表,我正在 mozilla sqlite manager 中检查该数据库。

谁能帮帮我。

提前谢谢你。

【问题讨论】:

您是否 100% 确定“数据库”变量包含您在 sqlite 管理器中检查的数据库的确切路径? 是的,我在 iphone 模拟器应用程序中添加了数据库,在我找到我的数据库的文档中,我将它添加到 sqlite manager 这个函数返回TRUE? 【参考方案1】:

您可以使用 sqlite3_exec() 方法代替 sqlite3_step()。

sqlite3_exec() 将执行您给出的任何查询。

我相信,它一定会对你有所帮助。

-(BOOL)createNewTable

    NSArray *array=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath=[array objectAtIndex:0];

filePath =[filePath stringByAppendingPathComponent:@"yourdatabase.db"];

NSFileManager *manager=[NSFileManager defaultManager];

BOOL success = NO;
if ([manager fileExistsAtPath:filePath]) 

    success =YES;

if (!success) 

    NSString *path2=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"yourdatabase.db"];
    success =[manager copyItemAtPath:path2 toPath:filePath error:nil];

createStmt = nil;
NSString *tableName=@"SecondTable";
if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) 
    if (createStmt == nil) 

        NSString *query=[NSString stringWithFormat:@"create table %@(rollNo integer, name text)",tableName];

        if (sqlite3_prepare_v2(database, [query UTF8String], -1, &createStmt, NULL) != SQLITE_OK) 
            return NO;
        
        sqlite3_exec(database, [query UTF8String], NULL, NULL, NULL);
        return YES;
    

return YES;

【讨论】:

【参考方案2】:

我也发布了一个答案,因为您的示例中没有错误处理,这似乎很有价值

初始化数据库:

    self.databasePath = [[NSString alloc]init];
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"myDB.db"];
    success = [fileManager fileExistsAtPath:writableDBPath];

    self.databasePath = writableDBPath;

    NSFileManager *filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: self.databasePath ] == NO)
    
        const char *dbpath = [self.databasePath UTF8String];

        if (sqlite3_open(dbpath, &myDB) == SQLITE_OK)
        
            NSLog(@"Database Opened");

            sqlite3_close(myDB);

         else 
            NSLog(@"Failed to open/create database");
        
    else 
//        NSLog(@"File exist");
    

调用创建表:

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

    if (sqlite3_open(dbpath, &myDB) == SQLITE_OK) 

        NSString *charsTableNameQuery = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(id INTEGER PRIMARY KEY, charName TEXT)",charsTableName];

        int results = 0;

        //create all chars tables
        const char *charsTableNameQuerySQL = [charsTableNameQuery UTF8String];
        sqlite3_stmt * charsTableNameStatment = nil;
        results = sqlite3_exec(myDB, charsTableNameQuerySQL, NULL, NULL, NULL);
        if (results != SQLITE_DONE) 
            const char *err = sqlite3_errmsg(tekkenDB);
            NSString *errMsg = [NSString stringWithFormat:@"%s",err];
            if (![errMsg isEqualToString:@"not an error"]) 
                NSLog(@"createTables-chartables error: %@",errMsg);
                return FALSE;
            
        

        sqlite3_finalize(charsTableNameStatment);
        sqlite3_close(myDB);

        return TRUE;
    else
        NSLog(@"database not opened");
    
    return FALSE;

【讨论】:

【参考方案3】: 创建带有桥接头的 objc 文件 (YOURFILENAME-Bridging-Header.h)

将此代码粘贴到您的 CustomDB.m 文件中。 ("CustomDB.m"

 #import "CustomDB.h"

        @implementation CustomDB

        - (void)createWith:(NSString *)strFileName;
        
            NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *docPath = [path objectAtIndex:0];

            dbPathString = [docPath stringByAppendingPathComponent:strFileName];
            NSLog(@"%@",dbPathString);
            char *error;

            NSFileManager *fileManager = [NSFileManager defaultManager];
            if (![fileManager fileExistsAtPath:dbPathString]) 
                const char *dbPath = [dbPathString UTF8String];

                //creat db here
                if (sqlite3_open(dbPath, &personDB)==SQLITE_OK) 
                    const char *sql_stmt = "CREATE TABLE IF NOT EXISTS PERSONS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE TEXT)";
                    sqlite3_exec(personDB, sql_stmt, NULL, NULL, &error);
                    sqlite3_close(personDB);
                
            
        
        -(void)insertInToDB:(NSString *)strQuery
            char *error;
            if (sqlite3_open([dbPathString UTF8String], &personDB)==SQLITE_OK) 
                NSString *inserStmt = [NSString stringWithFormat:@"%@", strQuery];
                const char *insert_stmt = [inserStmt UTF8String];

                if (sqlite3_exec(personDB, insert_stmt, NULL, NULL, &error)==SQLITE_OK) 
                    NSLog(@"Insert successfully");
                
                sqlite3_close(personDB);
            



        
        -(NSArray *)selectFromDB:(NSString *)strQuery
            sqlite3_stmt *statement;
            id result;
            NSMutableArray *thisArray = [[NSMutableArray alloc]init];

            if (sqlite3_open([dbPathString UTF8String], &personDB)==SQLITE_OK) 

                NSString *querySql = [NSString stringWithFormat:@"SELECT * FROM PERSONS"];
                const char* query_sql = [querySql UTF8String];

                if (sqlite3_prepare(personDB, query_sql, -1, &statement, NULL)==SQLITE_OK) 
                    while (sqlite3_step(statement)==SQLITE_ROW) 
                        NSMutableDictionary *thisDict = [[NSMutableDictionary alloc]init];
                        for (int i = 0 ; i < sqlite3_column_count(statement) ; i++) 
                            if(sqlite3_column_type(statement,i) == SQLITE_NULL)
                                continue;
                            
                            if (sqlite3_column_decltype(statement,i) != NULL &&
                                strcasecmp(sqlite3_column_decltype(statement,i),"Boolean") == 0) 
                                result = [NSNumber numberWithBool:(BOOL)sqlite3_column_int(statement,i)];
                             else if (sqlite3_column_type(statement,i) == SQLITE_INTEGER) 
                                result = [NSNumber numberWithInt:(int)sqlite3_column_int(statement,i)];
                             else if (sqlite3_column_type(statement,i) == SQLITE_FLOAT) 
                                result = [NSNumber numberWithFloat:(float)sqlite3_column_double(statement,i)];
                             else 
                                if((char *)sqlite3_column_text(statement,i) != NULL)
                                    result = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement,i)];
                                    [thisDict setObject:result
                                                 forKey:[NSString stringWithUTF8String:sqlite3_column_name(statement,i)]];
                                    result = nil;
                                
                            
                            if (result) 
                                [thisDict setObject:result
                                             forKey:[NSString stringWithUTF8String:sqlite3_column_name(statement,i)]];
                            
                        
                        [thisArray addObject:[NSDictionary dictionaryWithDictionary:thisDict]];
                    
                
            
            return thisArray;
        
        -(void)deleteFromDB:(NSString *)strQuery
            char *error;

            if (sqlite3_exec(personDB, [strQuery UTF8String], NULL, NULL, &error)==SQLITE_OK) 
                NSLog(@"Person deleted");
            
        
        @end

// paste this code in your CustomDB.h file. ("CustomDB.h" <- this is my file name)

#import <Foundation/Foundation.h>
#import <sqlite3.h>

@interface CustomDB : NSObject

    sqlite3 *personDB;
    NSString *dbPathString;

-(void)createWith:(NSString *)strFileName;
-(void)insertInToDB:(NSString*)strQuery;
-(NSArray *)selectFromDB:(NSString *)strQuery;
-(void)deleteFromDB:(NSString*)strQuery;
@end

不要忘记在您的桥接头中添加这一行 -> #import "CustomDB.h" 并在您的项目中添加 sqlite 框架... :)

在 sqlite 数据库中享受这些创建、插入、删除和选择查询:)

【讨论】:

【参考方案4】:

调用接收内存警告

(IBAction)findContact:(UIButton *)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)];
            _phoneNo.text = phoneField;
            _status.text = @"Match Found";
        else
            _status.text = @"Match not found";
            _address.text = @"";
            _phoneNo.text = @"";
        
        sqlite3_finalize(statement);
    
    sqlite3_close(contactDB);
  


【讨论】:

【参考方案5】:

NSString *docsDict; NSArray *dirPath;

//Get the Dictionary
dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
docsDict = dirPath[0];
NSLog(@"Path : %@",docsDict);

//Build the path to keep the database
_database = [[NSString alloc] initWithString:[docsDict stringByAppendingPathComponent:@"myUser.sql"]];

NSFileManager *fileMngr= [NSFileManager defaultManager];

if([fileMngr fileExistsAtPath:_database] == NO)
    
     const char *dbpath = [_database UTF8String];

  if(sqlite3_open(dbpath, &_DB) == SQLITE_OK)
       
        char *errorMassage;
        const char *sql_statement = "CREATE TABLE IF NOT EXISTS users (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRSTNAME TEXT, LASTNAME TEXT , MOBILENO TEXT)";

     if (sqlite3_exec(_DB,sql_statement,NULL,NULL,&errorMassage)!= SQLITE_OK)
        
            [self showUIAlertWithMessage:@"Failed to create the table" andTitle:@"error"];
        
            sqlite3_close(_DB);
     
  else
       
        [self showUIAlertWithMessage:@"Failed to open/create the table" andTitle:@"Error"];
       

【讨论】:

以上是关于sqlite3数据库建表如何建立一个日期型的数据?的主要内容,如果未能解决你的问题,请参考以下文章

MySql建表时日期类型的出理

Android SQLite3数据库操作问题

Android SQLite3数据库操作问题

如何将日期+时间保存和检索到 sqlite3 数据库中?

从 sqlite3 数据库中删除某些行

sqlite3简单操作