为什么数据没有插入数据库sqlite但显示数据,我采取静态路径并插入?

时间:2015-06-29 11:33:18

标签: ios sqlite insert

////此方法用于显示数据并且有效

    NSString *databasePath =[[[NSBundle mainBundle] bundlePath]stringByAppendingPathComponent:@"images.db"];

    if(sqlite3_open([databasePath UTF8String], &db)==SQLITE_OK){

        const char *sql = "SELECT * FROM IMAGEDATA";
        sqlite3_stmt *sqlStatement;
        if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
        {
           NSLog(@"Problem with prepare statement:  %s", sqlite3_errmsg(db));
        }
    else{

          while (sqlite3_step(sqlStatement)==SQLITE_ROW) {

               NSData *imageData = [[NSData alloc] initWithBytes:sqlite3_column_blob(sqlStatement, 1) length: sqlite3_column_bytes(sqlStatement, 1)];

               imagesfromdb =[UIImage imageWithData:imageData];
               NSLog(@"IMAGE :::%@",imagesfromdb);
              [databaseimage addObject:imagesfromdb];

             //imageData is saved favicon from website.

       }
    }
  }

/////此方法用于插入数据。

   const char *dbpath = [databasePath UTF8String];

  if(sqlite3_open(dbpath, &database)==SQLITE_OK)
  {

    NSData *imageData = UIImageJPEGRepresentation(chosenImage, 1);   
    const char* sqliteQuery = "INSERT INTO IMAGEDATA (NAME, IMAGE) VALUES (?, ?)";
   //sqlite3_stmt* statement;

   if( sqlite3_prepare_v2(database, sqliteQuery, -1, &statement, NULL) == SQLITE_OK )
   {
       sqlite3_bind_text(statement, 1, [fileName UTF8String], -1, SQLITE_TRANSIENT);
       sqlite3_bind_blob(statement, 2, [imageData bytes], (int)[imageData length], SQLITE_TRANSIENT);
       sqlite3_step(statement);
   }
  else NSLog( @"SaveBody: Failed from sqlite3_prepare_v2. Error is:  %s", sqlite3_errmsg(database) );

   // Finalize and close database.
   sqlite3_finalize(statement);

   }

这种方法不起作用我无法理解,但这种方法显示数据,直到我关闭应用程序。但之后数据将消失并且没有保存在db文件中

1 个答案:

答案 0 :(得分:0)

应用沙箱的mainBundle内的所有资源都具有readonly属性。这就是为什么在您的情况下,您能够读取数据但不能修改它。因此,您应首先将数据库文件复制到DocumentDirectory具有readwrite访问权限的write,然后您就可以在该数据库中执行DocumentDirectory操作。检查此问题以了解如何将数据库文件从mainBundle复制到<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %> <%@ taglib uri="http://liferay.com/tld/theme" prefix="theme" %> <%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %> <theme:defineObjects/> <portlet:defineObjects /> <portlet:resourceURL var="resourceURL"/> <script type="text/javascript"> function callServeResource(){ AUI().use('aui-io-request', function(A){ A.io.request('<%=resourceURL.toString()%>', { method: 'post', form: { id: 'fm' } }); }); } </script> <form name="fm" id="fm" enctype="multipart/form-data"> Full Name:<input type="text" name="fullName"/> <br/> Age:<input type="text" name="age"/> <br/> File:<input type ="file" name="fileName"/> <input type="button" value="Submit Form Data" onclick="callServeResource()"> </form>

How to copy sqlite database when application is launched in iOS?

您也可以按照此Tutorial了解所有步骤