2012-06-07 21 views
0

我正在使用此代碼插入數據,但在硬代碼中插入數據,但我需要從用戶端使用C++插入數據,任何人都可以堅持我:**C++:如何從客戶端使用sqlite3插入數據庫中的值

#include <iostream> 
using namespace std; 
#include "sqlite3.h" 
int main (int argc, const char * argv[]) { 

sqlite3 *db; 
sqlite3_open("test1.db", & db); 


string createQuery = "CREATE TABLE IF NOT EXISTS items (userid INTEGER PRIMARY KEY, ipaddr TEXT,username TEXT,useradd TEXT,userphone INTEGER,age INTEGER, " 
               "time TEXT NOT NULL DEFAULT (NOW()));"; 
    sqlite3_stmt *createStmt; 
    cout << "Creating Table Statement" << endl; 
    sqlite3_prepare(db, createQuery.c_str(), createQuery.size(), &createStmt, NULL); 
    cout << "Stepping Table Statement" << endl; 
    if (sqlite3_step(createStmt) != SQLITE_DONE) cout << "Didn't Create Table!" << endl; 

    string insertQuery = "INSERT INTO items (time, ipaddr,username,useradd,userphone,age) VALUES ('', '192.167.37.1','rahul da','benerghatta','9966524824',24);"; // WORKS! 
    sqlite3_stmt *insertStmt;`enter code here` 
    cout << "Creating Insert Statement" << endl; 
    sqlite3_prepare(db, insertQuery.c_str(), insertQuery.size(), &insertStmt, NULL); 
    cout << "Stepping Insert Statement" << endl; 
    if (sqlite3_step(insertStmt) != SQLITE_DONE) cout << "Didn't Insert Item!" << endl; 

    string selectQuery = "select * from items where ipaddr='192.167.37.1' & username= 'rahul';"; 
    sqlite3_stmt *selectStmt; 
    cout << "Creating select Statement" << endl; 
    sqlite3_prepare(db, selectQuery.c_str(), selectQuery.size(), &selectStmt, NULL); 
    cout << "Stepping select Statement" << endl; 
    if (sqlite3_step(selectStmt) != SQLITE_DONE) cout << "Didn't Select Item!" << endl; 

    cout << "Success!" << endl; 

    return 0; 
} 
+2

-1:您的問題不完整。請更詳細地解釋你正在嘗試做什麼。例如,你在說什麼「用戶端」。 –

+0

它不是用戶端它只是服務器端,我使用gsoap ...) – Satyam

回答

1

這真的取決於從你所得到的是存儲在數據什麼?如果你在特定的變量得到它,那麼你可以使用std::stringsteam到acheive你想要做什麼。

std::stringstream insertQuery; 
insertQuery << "INSERT INTO items (time, ipaddr,username,useradd,userphone,age)" 
       " VALUES ('" << time 
      << "', '" << ipaddr 
      << "', '" << username 
      << "', '" << useradd 
      << "', '" << userphone 
      << "', " << age << ")"; 
sqlite3_prepare(db, insertQuery.str().c_str(), insertQuery.size(), &insertStmt, NULL); 

注意stringstream上的附加調用.str()返回st環。

當然,您必須確保您的數據對您要插入的列的類型有效。如果你的輸入是直接來自用戶的話,那麼尤其如此 - 注意常見的陷阱,比如嵌入式引用和元字符。

+0

非常感謝:) – Satyam

相關問題