iOS下 Sqlite3  简单的代码例子


首先,导入libsqlite3.0.dylib库

 我们,来看一下.h文件


#import <sqlite3.h>
@interface ViewController : UIViewController
@property (assign,nonatomic)sqlite3* database;
-(IBAction)openDB;
-(IBAction)createTestList;
-(IBAction)insertTable;
-(IBAction)queryTable;
-(IBAction)deleteTable;
-(IBAction)updateTable;
@end




//获取document沙箱路径
-(NSString*)dataFilePath{
           
    NSArray *myPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *myDocPath = [myPaths objectAtIndex:0];
    NSString *filename = [myDocPath  stringByAppendingPathComponent:@"sqlite.db"];
    NSLog(@"%@",filename);
    return filename;//这里很神奇,可以定义成任何类型的文件,也可以不定义成.db文件,任何格局都行,定义成.sb文件都行,达到了很好的数据隐秘性
}



//创建,打开数据库
-(IBAction)openDB
{
    //获取数据库路径
    NSString* path = [self dataFilePath];
    //若是数据库存在,则用sqlite3_open直接打开(若是数据库不存在sqlite3_open会主动创建)
    sqlite3_open([path UTF8String], &_database);
}



//创建表
-(IBAction)createTestList
{
                                               
      const char *createSql="create table if not exists testTable(ID INTEGER PRIMARY KEY AUTOINCREMENT, testID int,testValue text,testName text)";
    sqlite3_exec(_database, createSql, NULL, NULL, NULL);
}





//插入数据
-(IBAction)insertTable
{
    const char *insertSql="INSERT INTO testTable(testID, testValue,testName) VALUES(120,'ew','45')";
    sqlite3_exec(_database, insertSql, NULL, NULL, nil);
                                         
}



//查看数据
-(IBAction)queryTable
{
    [self openDB];
    const char *selectSql="select testID,testName from testTable";
    sqlite3_stmt *statement;
    if (sqlite3_prepare_v2(_database, selectSql, -1, &statement, nil)==SQLITE_OK)
    {
        NSLog(@"select ok.");
        while (sqlite3_step(statement)==SQLITE_ROW)//SQLITE_OK SQLITE_ROW
        {
            int _id=sqlite3_column_int(statement, 0);
            NSString *name=[[NSString alloc] initWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding];
            NSLog(@"row>>id %i, name>> %@",_id,name);
        }
                                         
    }
                                     
}



//删除数据
-(IBAction)deleteTable
{
    [self openDB];
                                 
    const char *sql = "DELETE FROM testTable where testName='45'";
    sqlite3_exec(_database, sql, NULL, NULL, nil);
                              
}



//更改数据
-(IBAction)updateTable
{
                             
    [self openDB];
                             
    const char *sql = "update testTable set testName ='444' WHERE testID =120";
                           
    sqlite3_exec(_database, sql, NULL,NULL,NULL);
     sqlite3_close(_database);
                             
}



最后,在XIB中拖四个按钮与增、删、改、查 四个方法相关联


Hi,推荐文件给你 "Sqlite例子.zip" http://vdisk.weibo.com/s/HqLZq


http://pan.baidu.com/share/link?shareid=3059825140&uk=3189484501