SQLite数据库使用

  SQLite是一个小型的关系数据库,支持事务(原子性 atomicity、一致性Con sistency、隔离性Isolation和持久性Durability)简称ACID,触发器和大多数复杂的查询。
使用方式:
1、在命令行下或客户端软件如SQLite Database Browser工具创建所需要的数据表和默认数据,创建的文件为*.sqlite3文件,并将该文件引入到xcode的工程中。

2、在项目中配置SQLite的支持。
   1)选择项目的根目录。
   2)切换到 “Build Phases”标签下,展开“Link Binary With Libraries”。
   3)点击加号按钮,选择“libsqlite3.dylib”,将该文件拖到Frameworks组下,即可使用SQLite。

3、初始化数据连接:

// 数据库连接
static sqlite3 *database;


// 打开数据库(单例)
+ (id) singleton
{
	return [[[self alloc] init] autorelease];
}

-(id) init
{
	if ((self=[super init]) ) {
		if (database == nil)
		{

      [self createEditableCopyOfDatabaseIfNeeded];
			[self initDatabaseConnection];
		}
	}
	
	return self;
}

// Creates a writable copy of the bundled default database in the application Documents directory.
- (void) createEditableCopyOfDatabaseIfNeeded
{
    // First, test for existence.
    NSFileManager *fileManager = [NSFileManager defaultManager];
	
    NSString *writableDBPath = [self sqliteDBFilePath];
    // NSLog(@"%@", writableDBPath);
    if ([fileManager fileExistsAtPath: writableDBPath])
	{
		return;
	}
	
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kSQLiteFileName];
    NSError *error;
    
	if (![fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error])
	{
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

// 数据库文件路径
- (NSString *) sqliteDBFilePath
{	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"dblite.sqlite3"];
	NSLog(@"path = %@", path);
	
	return path;
}

// 初始化数据库连接,打开连接,并返回数据库连接(存放在database中)
- (void) initDatabaseConnection
{	
    if (sqlite3_open([[self sqliteDBFilePath] UTF8String], &database) != SQLITE_OK)
	{
        sqlite3_close(database);
        NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
    }
}

4、数据的增删改:
+ (void) editAlbum: (Album *) album
{
    sqlite3_stmt *statement;
    
    static char *sql = "UPDATE album SET title = ? WHERE albumid = ?";
    //static char *sql = "INSERT INTO album (albumid,title) VALUES (NULL,?)";
    // static char *sql = "DELETE FROM album WHERE albumid = ?";
    
    if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK)
    {
        NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(kAlbumDatabase));
    }
    sqlite3_bind_text(statement, 1, [album.title UTF8String], -1, NULL);
    sqlite3_bind_int(statement, 2, album.albumid);
    
    if (sqlite3_step(statement) == SQLITE_ERROR)
    {
        NSAssert1(0, @"Error: failed to edit album with message '%s'.", sqlite3_errmsg(kAlbumDatabase));
    }
    
    sqlite3_finalize(statement);
}

5、数据的查询:
+ (NSMutableArray *) fetchAlbums
{
    NSMutableArray *albums = [NSMutableArray array];
    
	// Compile the query for retrieving data.
	if (fetchAlbumsStatement == nil) {
		const char *sql = "SELECT albumid, title FROM album";
		if (sqlite3_prepare_v2(kAlbumDatabase, sql, -1, &fetchAlbumsStatement, NULL) != SQLITE_OK) {
			NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(kAlbumDatabase));
		}
	}
	
	while (sqlite3_step(fetchAlbumsStatement) == SQLITE_ROW)
	{
		Album *_album = [[Album alloc] init];
        
        _album.albumid = sqlite3_column_int(fetchAlbumsStatement, 0);
        _album.title = [NSString stringWithUTF8String:(char *)sqlite3_column_text(fetchAlbumsStatement, 1)];
		
		[albums addObject:_album];
        [_album release];
	}
	
	// Reset the statement for future reuse.
	sqlite3_reset(fetchAlbumsStatement);
    
    return albums;
}

6、关闭数据库:
// 关闭数据库连接
- (void) closeDatabase
{
  if (sqlite3_close(database) != SQLITE_OK)
	{
      NSAssert1(0, @"Error: failed to close database with message '%s'.", sqlite3_errmsg(database));
  }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Android中的SQLite数据库是一种轻量级的数据库,它可以在Android应用程序中存储和检索数据。SQLite数据库使用SQL语言来管理数据,可以在Android应用程序中创建、读取、更新和删除数据。使用SQLite数据库可以使应用程序更加高效和可靠,因为它可以在本地存储数据,而不需要访问网络。在Android中使用SQLite数据库需要使用SQLiteOpenHelper类来创建和管理数据库SQLiteOpenHelper类提供了一些方法来创建和升级数据库,以及插入、查询、更新和删除数据。在使用SQLite数据库时,需要注意数据类型、表结构、SQL语句等方面的问题,以确保数据的正确性和完整性。 ### 回答2: Android平台经常使用SQLite数据库来存储和管理本地数据。在本文中,我们将讨论如何在Android中使用SQLite数据库。 首先,在Android中使用SQLite数据库,我们需要创建一个SQLiteOpenHelper类。这个类用于创建和升级数据库。它包含了两个重要的方法:onCreate()和onUpgrade()。onCreate()方法将在首次创建数据库时被调用。onUpgrade()方法将在升级数据库时被调用。我们可以在这个类中定义表名,列名,数据库版本号和其他数据库相关信息。 接下来,在我们使用数据库前,需要实例化一个SQLiteOpenHelper类对象。这个对象用于打开或创建数据库。我们可以使用getReadableDatabase()和getWritableDatabase()方法来获取一个可读/写的数据库对象。 在获取数据库对象后,我们可以执行SQL命令来操作数据库。我们可以使用execSQL()方法来执行SQL命令。我们可以使用insert()、update()和delete()方法来执行增、删、改操作。我们可以使用rawQuery()方法来执行查询操作。 SQLiteOpenHelper类和SQLiteDatabase类并不是线程安全的。因此我们需要确保在使用时进行同步操作。我们可以使用synchronized关键字来达到同步效果。 在Android中,许多第三方的开源框架,如OrmLite、GreenDao和Realm等,提供了ORM(对象关系映射)的功能,使得数据库的操作更加简单和便捷。 总的来说,在Android中使用SQLite数据库可以轻松地存储和管理本地数据。SQLiteOpenHelper和SQLiteDatabase提供了丰富的API来操作数据库。ORM框架为我们提供了更加简便的数据库操作方式。因此,掌握Android中SQLite数据库使用非常重要。 ### 回答3: Android SQLite数据库是Android开发中最常用的数据库之一,它是一个基于文件的嵌入式关系数据库管理系统。SQLite在设计时考虑到了资源占用和运行效率,所以非常适合在移动设备上使用。下面将详细介绍如何使用Android SQLite数据库。 1. 创建数据库 首先需要创建一个SQLite数据库,通过SQLiteOpenHelper类来创建,传入的参数主要是数据库版本号和数据库名称。在SQLiteOpenHelper的子类中重写onCreate方法来创建表格和一些初始化操作。 2. 执行SQL语句 在SQLiteOpenHelper的子类中重写onUpgrade方法来执行升级操作,可以通过执行ALTER TABLE语句来修改表格结构,并通过DROP TABLE语句删除表格。除此之外,在应用中也可以通过SQLiteDataBase对象的execSQL方法来执行SQL语句,如插入、删除或修改数据等。 3. 增删改查操作 增加(insert):通过SQLiteDataBase对象的insert方法来实现,在方法中传入表名和map对象,map对象中存储数据的键值对。 删除(delete):同样通过SQLiteDataBase对象的delete方法来实现,传入表名和删除条件。 修改(update):也是通过SQLiteDataBase对象的update方法来实现,同时传入修改的数据及条件。 查询(query):同样通过SQLiteDataBase对象的query方法来实现,传入要查询的表名、查询的列、查询条件等参数即可。 4. 事务操作 SQlite数据库支持事务操作,可以在一组操作中,只要有一个操作出现问题,就可以将之前的操作全部回滚,以保证数据的完整性和一致性。 以上就是android-sqlite数据库使用方法,当然还有很多细节需要注意,例如:表格的设计、SQL语句的优化等。熟练掌握SQLite使用,可以帮助开发者更好地管理应用数据,提高应用性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值