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

半城伤御伤魂 提交于 2019-12-02 04:46:11

问题


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.sqlite which is used as a template for all newly created databases. I want to use it, not a creation script, so that I have to maintain only one file, the empty database template itself.

I would like to create an in-memory database with the same structure based on that template file.

I know I can open the database and read it's structure, then create the database manually in memory. If possible, I would like to be able to do it in a more automatic way.


回答1:


You could use the .dump command of the command-line shell do create a bunch of SQL commands that you can execute.

Alternatively, you can use the backup API to copy the template into a new database.




回答2:


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;
}


来源:https://stackoverflow.com/questions/17020730/how-to-create-an-in-memory-database-with-schema-based-on-an-existing-file-databa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!