[SQLite3] 파일로 저장된 DB를 메모리DB로 로드

前端之家收集整理的这篇文章主要介绍了[SQLite3] 파일로 저장된 DB를 메모리DB로 로드前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

(From: http://blog.daum.net/_blog/BlogView.do?blogid=0Idq4&articleno=8429408#ajax_history_home)

다음은 "파일로 저장된 sqlite3 데이터베이스를 메모리 데이터베이스 (:memory:)로 로드하는 방법" 에 대해서 설명하고 있습니다.

이와 관련된 좀 더 자세한 내용은http://www.sqlite.org/backup.html 를 참고하시면 됩니다.

1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <assert.h>
4 #include "sqlite3.h"
5
6 #pragma warning(disable:4996)
7
8 int LoadDatabase ( sqlite3 * memDb, const char * zFilename)
9 {
10 int rc; /* Function return code */
11 sqlite3 * fileDB; /* Database connection opened on zFilename */
12 sqlite3_backup * pBackup; /* Backup object used to copy data */
13
14 /* Open the database file identified by zFilename. Exit early if this fails
15 ** for any reason. */
16 rc = sqlite3_open ( zFilename,& fileDB);
17 if ( rc== sqlITE_OK ){
18
19 /* Set up the backup procedure to copy from the "main" database of
20 ** connection pFile to the main database of connection pInMemory.
21 ** If something goes wrong,pBackup will be set to NULL and an error
22 ** code and message left in connection pTo.
23 **
24 ** If the backup object is successfully created,call backup_step()
25 ** to copy data from pFile to pInMemory. Then call backup_finish()
26 ** to release resources associated with the pBackup object. If an
27 ** error occured,then an error code and message will be left in
28 ** connection pTo. If no error occured,then the error code belonging
29 ** to pTo is set to sqlITE_OK.
30 */
31 pBackup = sqlite3_backup_init ( memDb, "main" , fileDB, "main" );
32 if ( pBackup ){
33 ( void ) sqlite3_backup_step ( pBackup,- 1 );
34 ( void ) sqlite3_backup_finish ( pBackup);
35 }
36 rc = sqlite3_errcode ( memDb);
37 }
38
39 /* Close the database connection opened on database file zFilename
40 ** and return the result of this function. */
41 ( void ) sqlite3_close ( fileDB);
42 return rc;
43 }
44
45 int main ( int argc, char ** argv)
46 {
47 sqlite3 * db = NULL;
48 sqlite3_stmt * stmt = NULL;
49
50 assert ( sqlite3_open_v2 ( ":memory:" ,& db, sqlITE_OPEN_READWRITE | sqlITE_OPEN_CREATE, NULL) == sqlITE_OK);
51 assert ( LoadDatabase ( db, "./test.db" ) == sqlITE_OK);
52 assert ( sqlite3_prepare ( db, "select id,name from address;" ,- 1 ,& stmt, NULL) == sqlITE_OK);
53
54 while ( sqlite3_step ( stmt) == sqlITE_ROW )
55 {
56 // do something with column
57 sqlite3_column_int ( stmt, 0 );
58 sqlite3_column_text ( stmt, 1 );
59 }
60
61 assert ( sqlite3_close ( db) == sqlITE_OK);
62 return 0 ;
63 }

猜你在找的Sqlite相关文章