How to create an in-memory database with schema based on an existing file database

后端 未结 2 802
轮回少年
轮回少年 2021-01-23 06:10

I have an existing database which structure is used accross the whole application. Instances of the databases are periodically rotated. I have a database file template.sql

2条回答
  •  心在旅途
    2021-01-23 06:53

    As a quick solution for all seeking answer to this question: a bit of C code that does the trick:

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

提交回复
热议问题