數據庫是這樣設計的:用內存保存數據,以提高增刪查改的速度,同時把數據寫入磁盤,讓數據落地。
如果不刪除數據庫里的數據,隨着數據不斷地添加到數據庫,數據庫越來越大,RES內存也越來越大。
見測試代碼a.c:
/************************************************************************* * File: a.cpp * Brief: * Author: * Created Time: Tue 05 Jan 2016 09:53:18 AM CST ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include"sqlite3.h" #define LOG_MSG(d,a,...) printf(a,##__VA_ARGS__) sqlite3* m_SQLite3Conn=NULL; int m_nextserial=0; char m_sql[255]; int SQLiteExcute(const char* sql) { if (NULL == m_SQLite3Conn || NULL == sql || strcmp(sql, "") == 0) { return -1; } char* err_msg = NULL; if(sqlite3_exec(m_SQLite3Conn,sql,NULL,NULL,&err_msg) != SQLITE_OK) { LOG_MSG(err_LogLevel,"sqlite3_exec fail.err=%s, sql=%s",err_msg,sql); sqlite3_free(err_msg); return -2; } int rows=sqlite3_changes(m_SQLite3Conn); sqlite3_free(err_msg); return rows; } int ainit() { char* sql; sql="create table if not exists DeviceInfo(" "serial TEXT PRIMARY KEY, " "ip TEXT, " "user TEXT, " "pwd TEXT);"; SQLiteExcute(sql); sql="create index idxT1 on DeviceInfo(ip);"; SQLiteExcute(sql); } int aopen() { int ret = sqlite3_open_v2("./db.db",&m_SQLite3Conn, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX, NULL); if(ret != SQLITE_OK){ LOG_MSG(err_LogLevel,"open sqlite db failure[%s]", sqlite3_errmsg(m_SQLite3Conn)); return -2; } ret=sqlite3_threadsafe(); if (!ret) { LOG_MSG(err_LogLevel,"sqlite3 is not thread safe"); } return 0; } int ainsert(char* ip,char* user,char* pwd) { char id[255]; sprintf(id,"id-%d",m_nextserial++); sprintf(m_sql, "insert into DeviceInfo(serial, ip, user, pwd) " "values('%s', '%s', '%s', '%s') ", id, ip, user, pwd); int ret=SQLiteExcute(m_sql); printf("id=%s\n",id); return ret; } int adelete() { char id[255]; sprintf(id,"id-%d",m_nextserial-10); sprintf(m_sql, "delete from DeviceInfo where serial='%s' ", id); int ret=SQLiteExcute(m_sql); printf("delete id=%s\n",id); return ret; } int main() { aopen(); ainit(); printf("hello pid=%d\n",getpid()); usleep(10000*900); while(1) { ainsert("192.168.1.12","user2","pwd2"); /* ---內存持續增加研究--- 原來,數據庫是這樣設計的:用內存保存數據,以提高增刪查改的速度,同時把數據寫入磁盤,讓數據落地。 如果不刪除數據庫里的數據,隨着數據不斷地添加到數據庫,數據庫越來越大,RES內存也越來越大。 開啟如下的刪除數據庫數據的功能代碼后,雖然不斷地有新數據添加到數據庫,但也一直從數據庫中刪除着數據。 數據庫的數據總量一直保持10條數據的總量,VIRT、RES、SHR長期保存不變。 所以,數據庫里已經使用過的數據,應該盡量刪除。 或者,每次操作數據庫的數據后,要關閉數據庫連接,下一次要操作數據庫的數據時,再打開連接。 即重復如下邏輯:"打開數據->操作數據庫數據->關閉數據庫"。 當然,數據庫文件也要定期縮減。因為即使你刪除了數據庫的數據,sqlite3也不會自動縮減數據庫。 所以,需要定期執行sql縮減數據庫文件命令:"vacuum;"。 */ //adelete(); //如果不注析此語句,內存會不斷地增加;如果注析,內存一直保持穩定不變。 usleep(2000); } return 0; }
編譯運行,使用如下命令查看進程內存情況,發現內存一直穩定不變。
top -p precessID
完成測試工程見:百度網盤\軟件源碼\testsqlite.tar.gz
完。