2015-07-06 68 views
0

這裏是我在社會上第二個職位,原諒我,如果我忘了補充一點,只是讓我知道:保存文本SQLITE3,C++

我想在C++中能夠保存做一個程序文本(我想保存代碼)使用sqlite3在數據庫中。目前我做了一個wxWidget程序,它調用DLL中的一些函數,並且這些函數與數據庫交互。

我想製作的數據庫非常簡單,它在一個表(id,name,ref)中有3列。當我想要保存大量含有可能與sql查詢衝突的simblos的文本(我想將文件保存到數據庫中,例如在「ref」列中)時,我的問題就出現了。

我使用的主要是sqlite3_exec函數,因爲函數sqlite3_prepare_v2sqlite_bind,sqlite3_step使我崩潰了我工作的DLL。

我懷疑:我可以直接保存任何大小的文本,而不需要考慮它是否帶有符號?我該怎麼做?

更多信息:我在C++中使用代碼:block(13.12)製作sqlite3函數的DLL並使用MinGW工具鏈。 (Windows 7的)。

這是我使用插入函數的例子:

int DLL_EXPORT add_item(sqlite3* db, string tbname,string col,string item) 
{ 
    char* db_err = 0; 
    if (tbname==std::string()||col==std::string()||item==std::string()) 
     throw std::invalid_argument("stoi: invalid argument table name"); 


     char buf[200]; 
     sprintf(buf,"insert into %s (%s) values ('%s');", tbname.c_str(), col.c_str(),item.c_str()); 
     int n = sqlite3_exec(db, buf, NULL, 0, &db_err); 
     dsperr(&db_err); 
     if(n != SQLITE_OK) 
     { 
     //throw something 
     } 

    return 0; 
} 

預先感謝您。

+0

如果調用'sqlite3_prepare_v2'崩潰,那麼這段代碼有可能崩潰也說不定。無論如何,一個200字節的緩衝區將不允許你保存大文本,並且這個代碼允許[SQL注入](https://en.wikipedia.org/wiki/SQL_injection);你應該使用[sqlite3_mprintf()](http://www.sqlite.org/c3ref/mprintf.html)。 –

+0

非常感謝,這正是我正在爲此而努力。稍後當我確定工作正常時,我會在這裏粘貼我的代碼。 :) – JoseleMG

回答

0

感謝到CL.爲最多評論

// Add one text to a table 
// The column must be specify 
// 
int DLL_EXPORT add_text(sqlite3* db, string tbname,string col,string id,string item) 
{ 
    char* db_err = 0; 
    if (tbname==std::string()||col==std::string()||item==std::string()) 
     throw std::invalid_argument("stoi: invalid argument table name"); 

    char *zSQL = sqlite3_mprintf("UPDATE %q SET %q=(%Q) WHERE id=%q", tbname.c_str(),col.c_str() ,item.c_str(),id.c_str()); 
    int n = sqlite3_exec(db, zSQL, NULL, 0, &db_err); 
    dsperr(&db_err); 
    sqlite3_free(zSQL); 
    if(n != SQLITE_OK) 
     { 
     // throw something 
     } 
    return 0; 
}