十月 28, 2011

iPhone开发:如何直接用Object-C连接数据库

Written by

iphone开发连数据库一般有两种

1.core data 这种是可视化的存储方式,不带sql语句的,应该是官方封装好了
2.直接通过sql语句连接sqlite:
[code lang="c"]
- (BOOL) databaseTest
{
//数据库操作
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"mydb.db"];//查找db文件返回其path
NSLog(path);//打印db文件的路径
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL find = [fileManager fileExistsAtPath:path];
if(find){
NSLog(@"Sucess:find dn file.");
if(sqlite3_open([path UTF8String], &database_) == SQLITE_OK)//打开数据库
{

//打开数据库成功
NSLog(@"Sucess:open database sucess.");
/////////////////////////////////////////////////////////////////////////////////
//这里进行数据库操作
/////////////////////////////////////////////////////////////////////////////////
//////////////////////////1.插入数据////////////////////////////////////////////////
//SQL查询语句
char *sql = "INSERT INTO students (name) VALUES(?)";
//会话
sqlite3_stmt *statement;
//调制一个会话
int success = sqlite3_prepare_v2(database_, sql, -1, &statement, NULL);
if (success != SQLITE_OK) {
NSLog(@"Error: failed to insert:channels");
}
//绑定数据

sqlite3_bind_text(statement, 1, "Kevin", -1, SQLITE_TRANSIENT);//注意此处的字符串为旧字符串
success = sqlite3_step(statement);
sqlite3_finalize(statement);
if (success == SQLITE_ERROR) {
NSLog(@"Error: failed to insert into the database with message.");
}

//2.查询数据
statement = nil;
char *sql_select= "SELECT name FROM students";
if (sqlite3_prepare_v2(database_, sql_select, -1, &statement, NULL) != SQLITE_OK) {
NSLog(@"Error: failed to prepare statement with message:get channels.");
}
//查询结果集中一条一条的遍历所有的记录,这里的数字对应的是列值。
while (sqlite3_step(statement) == SQLITE_ROW) {
char* name = (char*) sqlite3_column_text(statement, 0);//第一列数据,注意此处师从0开始的
NSString *nameNs=[[NSString alloc] initWithUTF8String:name];
NSLog(nameNs);
[nameNs release];

}
sqlite3_finalize(statement);

//关闭数据库
sqlite3_close(database_);
return YES;
}
else
{
sqlite3_close(database_);
NSLog(@"Error: open database file.");
return NO;
}

return NO;
}
}
[/code]

Category : C/C++iOSiPhone

Tags :

发表评论

电子邮件地址不会被公开。

Proudly powered by WordPress and Sweet Tech Theme