iOS学习笔记---数据库SQLite3的基本操作并讲内容显示在tableView中

之前有做过一段时间的android,由于主要是做前端,对数据的了解就不是很深,而且觉得比较难,但是自己也清除SQLite是肯定要搞懂的,现在做IOS了,就想趁这个机会跨过这个大坑。让我没想到的是ios用的SQLite3比android用的SQLite还要麻烦。。。。

花了两天时间写了个基本操作的demo,并结合tableView显示数据,这样就不用使用那些什么数据库管理软件什么的来管理了。。。。感觉不能看的东西写起来真蛋疼~···

先看看效果图吧~···


·好了,废话不多说了,具体看代码吧····注释也应该够详细了······


主要的.m文件

//
//  ViewController.m
//  SQLite3Test
//
//  Created by yaodd on 13-7-9.
//  Copyright (c) 2013年 jitsun. All rights reserved.

//  数据库的基本操作,包括创建,插入,查询,删除
//  将数据库里的内容动态显示在tableView
//  点击按钮则添加一行数据,点击tableView中某一行则删除一条数据,同时如果按home键使程序在后台运行也会将当前数据添加进数据库中

#import "ViewController.h"
#import <sqlite3.h>
#import "cellItem.h"
#import "PeopleCell.h"

@implementation ViewController
@synthesize arrPeople;
@synthesize fieldAddress;
@synthesize fieldAge;
@synthesize fieldCity;
@synthesize fieldName;
@synthesize insertButton;
@synthesize PeopleTableView;
- (NSString *)dataFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                         NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:@"data.sqlite"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //tableView中显示的数据包装
    arrPeople = [[NSMutableArray alloc]init];
    
    //建立表(程序第一次运行时建立)
    sqlite3 *database;
    if (sqlite3_open([[self dataFilePath] UTF8String], &database)
        != SQLITE_OK) {
        sqlite3_close(database);
        NSAssert(0, @"Failed to open database");
    }
    //建立表的SQL语句,主键为ROW,自增;其他键为NAME,AGE,ADDRESS,CITY。
    NSString *createSQL = @"CREATE TABLE IF NOT EXISTS PEOPLE "
    "(ROW INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE INTEGER, ADDRESS TEXT, CITY TEXT);";
    //将出错信心保存在errorMsg中
    char *errorMsg;
    if (sqlite3_exec (database, [createSQL UTF8String],
                      NULL, NULL, &errorMsg) != SQLITE_OK) {
        sqlite3_close(database);
        //如果出错,则输出errorMsg
        NSAssert(0, @"Error creating table: %s", errorMsg);
    }
    //查询数据库,并以ROW排序
    NSString *query = @"SELECT ROW, NAME, AGE, ADDRESS, CITY FROM PEOPLE ORDER BY ROW";
    sqlite3_stmt *statement;//至于这个参数,网上的说法“这个相当于ODBC的Command对象,用于保存编译好的SQL语句”;
    if (sqlite3_prepare_v2(database, [query UTF8String],
                           -1, &statement, nil) == SQLITE_OK)
    {
        while (sqlite3_step(statement) == SQLITE_ROW) {//对表中的数据进行遍历,并转为item加入arrPeople中
            NSLog(@"%d",arrPeople.count);
            cellItem *item = [[cellItem alloc]init];
            int row = sqlite3_column_int(statement, 0);
            char *nameChar = (char *)sqlite3_column_text(statement, 1);
            int age = sqlite3_column_int(statement,2);
            char *addressChar = (char *)sqlite3_column_text(statement,3);
            char *cityChar = (char *)sqlite3_column_text(statement, 4);
            NSLog(@"row:%d name:%s age:%d add:%s city:%s",row,nameChar,age,addressChar,cityChar);
            item.row = [[NSString alloc] initWithFormat:@"%d",row];
            item.age = [[NSString alloc] initWithFormat:@"%d",age];
            item.name = [[NSString alloc] initWithUTF8String:nameChar];
            item.address = [[NSString alloc] initWithUTF8String:addressChar];
            item.city = [[NSString alloc] initWithUTF8String:cityChar];
            [arrPeople addObject:item];
            
        }
        sqlite3_finalize(statement);//结束之前清除statement对象,
    }
    sqlite3_close(database);//关闭数据库
    
    //这几行代码是当程序在后台运行时执行的函数
    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(applicationWillResignActive:)
     name:UIApplicationWillResignActiveNotification
     object:app];
    
    //插入数据的按钮;按多次就会插入多条
    [insertButton addTarget:self action:@selector(insertButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
}
//后台运行时执行的函数,也是执行插入数据的操作
- (void)applicationWillResignActive:(NSNotification *)notification
{
    [self insertData];//插入数据函数
}
//插入数据的按钮响应器
- (void)insertButtonPressed:(id)sender
{
    [self insertData];//插入数据函数
}
//插入数据函数的实现,用的是绑定变量的方法。
- (void)insertData
{
    int count = arrPeople.count;
    sqlite3 *database;
    if (sqlite3_open([[self dataFilePath] UTF8String], &database)
        != SQLITE_OK) {
        sqlite3_close(database);
        NSAssert(0, @"Failed to open database");
    }
    cellItem *item = [[cellItem alloc] init];
    item.row = [[NSString alloc]initWithFormat:@"%d",count];
    item.name = fieldName.text;
    item.age = fieldAge.text;
    item.address = fieldAddress.text;
    item.city = fieldCity.text;
    //插入或更新一行,不指定主键ROW··则ROW会自增
    //INSERT OR REPLACE实现了插入或更新两个操作
    char *update = "INSERT OR REPLACE INTO PEOPLE (NAME, AGE, ADDRESS, CITY) "
    "VALUES (?, ?, ?, ?);";
    char *errorMsg = NULL;
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(database, update, -1, &stmt, nil)
        == SQLITE_OK) {
        
        sqlite3_bind_text(stmt, 1, [item.name UTF8String], -1, NULL);
        sqlite3_bind_int(stmt, 2, [item.age intValue]);
        sqlite3_bind_text(stmt, 3, [item.address UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 4, [item.city UTF8String], -1, NULL);
        
    }
    if (sqlite3_step(stmt) != SQLITE_DONE)
        NSAssert(0, @"Error updating table: %s", errorMsg);
    sqlite3_finalize(stmt);//结束之前清除statement变量
    
    sqlite3_close(database);//关闭数据库
    [arrPeople addObject:item];//tableView里的数据的增加
    [self.PeopleTableView reloadData];//动态更新tableView
    
    NSLog(@"insert %d",count);

}
//删除表中row = rowId的那一行
- (void)deleteData:(int)rowId
{
    sqlite3 *database;
    if (sqlite3_open([[self dataFilePath] UTF8String], &database)
        != SQLITE_OK) {
        sqlite3_close(database);
        NSAssert(0, @"Failed to open database");
    }
    char *errmsg;
    NSString *deleteRow = [[NSString alloc]initWithFormat:@"DELETE FROM PEOPLE WHERE ROW = %d",rowId];
    sqlite3_exec(database, [deleteRow UTF8String], NULL, NULL, &errmsg);
    NSLog(@"%s",errmsg);
    sqlite3_close(database);

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arrPeople count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
       
    static NSString *PeopleCellIdentifier = @"PeopleCellIdentifier";
    //自定义的TableViewCell
    PeopleCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             PeopleCellIdentifier];
    if (cell == nil) {
        cell = [[PeopleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: PeopleCellIdentifier];
    }
    
    NSInteger row = [indexPath row];
    cellItem *item = [arrPeople objectAtIndex:row];
    cell.row.text = [[NSString alloc]initWithFormat:@"%d",row];
    cell.name.text = item.name;
    cell.age.text = item.age;
    cell.address.text = item.address;
    cell.city.text = item.city;
    
    
    return  cell;
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 67;
}

#pragma Table view delegate

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //点击某一行则删除改行
    NSInteger row = [indexPath row];
    cellItem *item = [arrPeople objectAtIndex:row];
    [self deleteData:[item.row intValue]];//数据库中删除
    [arrPeople removeObjectAtIndex:row];//tableView数据中删除
    [self.PeopleTableView reloadData];//动态更新tableView
}

@end


由于这个demo还用到牵涉到了tableView,因此project里面还有一些数据类型文件和cell文件

完整工程包请移步 http://download.csdn.net/detail/kekeqiaokeli/5727291 下载。谢谢支持!


好好学习,天天向上~···

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的示例代码,展示如何将Qt的TableView控件链接到SQLite数据库,并在界面上显示数据库内容: ```python from PyQt5.QtWidgets import QApplication, QTableView, QVBoxLayout, QWidget from PyQt5.QtSql import QSqlDatabase, QSqlTableModel import sys class MainWindow(QWidget): def __init__(self): super().__init__() # 初始化数据库 self.db = QSqlDatabase.addDatabase('QSQLITE') self.db.setDatabaseName('my_database.db') self.db.open() # 创建数据模型 self.model = QSqlTableModel(self) self.model.setTable('my_table') self.model.select() # 创建TableView控件 self.table_view = QTableView() self.table_view.setModel(self.model) # 创建布局 layout = QVBoxLayout() layout.addWidget(self.table_view) # 设置窗口布局 self.setLayout(layout) if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_()) ``` 在这个示例,我们首先初始化了一个SQLite数据库,并创建了一个名为`my_table`的表。然后,我们创建了一个`QSqlTableModel`对象,并将其链接到数据库的`my_table`表。我们还创建了一个`QTableView`控件,并将数据模型设置为其数据源。最后,我们创建了一个垂直布局,并将TableView控件添加到其,最终将布局设置到窗口。 运行程序后,您将看到TableView控件显示数据库的所有记录。您可以使用SQLite命令行工具或其他工具向数据库添加、删除或修改记录,然后在程序刷新TableView控件,以显示最新的记录。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值