iPhone中支持通过sqlite3来访问iPhone本地的数据库。
具体使用方法如下
首先是设置项目文件,在项目中添加iPhone版的sqlite3的数据库的开发包,在项目下的Frameworks点击右键,然后选择libsqlite3.0.dylib文件。
libsqlite3.0.dylib文件地址:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.sdk/usr/lib/libsqlite3.0.dylib
2,代码中的操作:
那么接下来是代码了。
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"database_name"];
const char *sql = " SELECT * FROM table_name WHERE pk=? and name=?";
sqlite3_prepare_v2(database,sql,-1,&stmt,NULL);
4邦定参数
sqlite3_bind_int(stmt,1,1);
// 邦定第二个字符串参数
sqlite3_bind_text(stmt,2,[title UTF8String],sqlITE_TRANSIENT);
5执行sql文
6释放sql文资源
sqlite3_close(database);
- (BOOL)opensqlite
{
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *thePath1 = [paths1 objectAtIndex:0];
NSLog(@"%@",thePath1);
NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,YES);
NSString *cachesDirectory2 = [paths2 objectAtIndex:0];
NSLog(@"%@",cachesDirectory2);
NSString *paths = [[NSBundle mainBundle] resourcePath];
NSLog(@"%@",paths);
NSString *xmlFile = [paths stringByAppendingPathComponent:@"Provin.db"];
if (sqlite3_open([xmlFile UTF8String],&database) != sqlITE_OK) {
sqlite3_close(database);
database = NULL;
return NO;
}
return YES;
}
- (void)closesqlite
{
if (database!=nil) {
sqlite3_close(database);
database = NULL;
}
}
-(void)searchPrivince
{
[arrProvince removeAllObjects];
NSString* selectsql1 = [[NSString alloc] initWithFormat:@"select province,provinceID from province"];
sqlite3_stmt* statement;
if (sqlite3_prepare_v2(database,[selectsql1 UTF8String],-1,&statement,nil) == sqlITE_OK) {
while (sqlite3_step(statement)== sqlITE_ROW) {
char* province = (char*)sqlite3_column_text(statement,0);
char* provinceid = (char*)sqlite3_column_text(statement,1);
NSString* provinceName = [[NSString alloc] initWithCString:province encoding:NSUTF8StringEncoding];
NSString* provinceID = [[NSString alloc] initWithCString:provinceid encoding:NSUTF8StringEncoding];
provinceData = [[PhysicalBuyProvinceData alloc]init];
provinceData.strProvinceName = provinceName;
provinceData.strProvinceID = provinceID;
[arrProvince addObject:provinceData];
[provinceID release];
[provinceName release];
[provinceData release];
}
}
[selectsql1 release];
sqlite3_finalize(statement);
}