您好我正在开发一个包含2个表的数据库dbmain 我的代码
NSString *docsDir;
NSArray *dirPaths;
dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// docsDir=[dirPaths objectAtIndex:0];
docsDir = dirPaths[0];
databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@"dbDare.db"]];
NSFileManager *filemgr=[NSFileManager defaultManager];
if([filemgr fileExistsAtPath:databasePath]==NO)
{
const char *dbpath=[databasePath UTF8String];
if(sqlite3_open(dbpath, &contactDB)==SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS tblUser(ID INTEGER PRIMARY KEY AUTOINCREMENT, StrName TEXT,Strusername TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed to create table"
message:@"Failed to create table"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
//status.text = @"Failed to create table";
}
char *errMsg1;
const char *sql_stmt1 =
"CREATE TABLE IF NOT EXISTS tblVanish (ID INTEGER PRIMARY KEY AUTOINCREMENT, strfilepath TEXT,datesaved TEXT)";
if (sqlite3_exec(contactDB, sql_stmt1, NULL, NULL, &errMsg1) != SQLITE_OK)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed to create table"
message:@"Failed to create table"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
//status.text = @"Failed to create table";
}
sqlite3_close(contactDB);
} else {
// status.text = @"Failed to open/create database";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed to create open/create database"
message:@"Failed to create open/create database"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
在向表中添加记录后,我可以使用lita软件查看行 但是在通过此代码重新检索行时
const char *dbpath=[databasePath UTF8String];
int iVal=0;
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = @"SELECT Strusername FROM tblUser";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
while (sqlite3_step(statement) == SQLITE_ROW) {
strname = [NSString stringWithFormat:@"Welcome %@" ,[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)]];
}
} else {
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
我无法获取任何东西,因为使用ios在表格中没有显示行但我可以使用lita看到表格内的行,请建议我在哪里弄错了
答案 0 :(得分:3)
您将数据库文件复制到文档目录的哪个位置?
这种情况对我来说很奇怪:
if([filemgr fileExistsAtPath:databasePath]==NO)
如果那里不存在数据库,为什么不将它复制到文档目录?
此外,您在if条件中创建表,意味着您正在尝试在不存在的db文件上创建表。
您可能希望先复制db
文件,然后需要创建表格。
或强>
您需要更改条件,如:
if([filemgr fileExistsAtPath:databasePath]== YES)