Saving to disk an in-memory database

前端 未结 3 773
情深已故
情深已故 2020-12-08 08:00

I made a database through sqlite in c++.

The db has been created in memory (using the \":memory:\" parameter insted of a filename), in order to have a very quick be

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 08:33

    If you do not have enough time to read the whole documentation posted by @NickDandoulakis's answer, just copy and paste the below function (already mentioned in the link) in your code:

    int loadOrSaveDb(sqlite3 *pInMemory, const char *zFilename, int isSave) 
    {
       int rc;                   /* Function return code */
       sqlite3 *pFile;           /* Database connection opened on zFilename */
       sqlite3_backup *pBackup;  /* Backup object used to copy data */
       sqlite3 *pTo;             /* Database to copy to (pFile or pInMemory) */
       sqlite3 *pFrom;           /* Database to copy from (pFile or pInMemory) */
    
       rc = sqlite3_open(zFilename, &pFile);
       if (rc == SQLITE_OK) 
       {
    
          pFrom = (isSave ? pInMemory : pFile);
          pTo = (isSave ? pFile : pInMemory);
    
          pBackup = sqlite3_backup_init(pTo, "main", pFrom, "main");
          if (pBackup) {
             (void)sqlite3_backup_step(pBackup, -1);
             (void)sqlite3_backup_finish(pBackup);
          }
          rc = sqlite3_errcode(pTo);
       }
    
       (void)sqlite3_close(pFile);
       return rc;
    }
    

    and then for saving the data of your SQLite db (in memory) into a file call:

    loadOrSaveDb(db_con, target_file, 1);
    

    Which db_con is your database connection object pointer and target_file is the target file address.

    Remark: If you want to load a SQLite database file into memory, just run:

    loadOrSaveDb(db_con, target_file, 0);
    

提交回复
热议问题