SQLite Blob insertion c++

后端 未结 1 1001
终归单人心
终归单人心 2021-01-02 10:30

After visiting dozens of websites containing info about SQLite I still cannot find a solution to fix an error while binding a blob. Here is the table decleration:

         


        
相关标签:
1条回答
  • 2021-01-02 11:12

    Your code has too many errors to count.

    Try something like this:

    int InsertFile(const string& db_name)
    {
        ifstream file("Sql.pdf", ios::in | ios::binary);
        if (!file) {
            cerr << "An error occurred opening the file\n";
            return 12345;
        }
        file.seekg(0, ifstream::end);
        streampos size = file.tellg();
        file.seekg(0);
    
        char* buffer = new char[size];
        file.read(buffer, size);
    
        sqlite3 *db = NULL;
        int rc = sqlite3_open_v2(db_name.c_str(), &db, SQLITE_OPEN_READWRITE, NULL);
        if (rc != SQLITE_OK) {
            cerr << "db open failed: " << sqlite3_errmsg(db) << endl;
        } else {
            sqlite3_stmt *stmt = NULL;
            rc = sqlite3_prepare_v2(db,
                                    "INSERT INTO ONE(ID, NAME, LABEL, GRP, FILE)"
                                    " VALUES(NULL, 'fedfsdfss', NULL, NULL, ?)",
                                    -1, &stmt, NULL);
            if (rc != SQLITE_OK) {
                cerr << "prepare failed: " << sqlite3_errmsg(db) << endl;
            } else {
                // SQLITE_STATIC because the statement is finalized
                // before the buffer is freed:
                rc = sqlite3_bind_blob(stmt, 1, buffer, size, SQLITE_STATIC);
                if (rc != SQLITE_OK) {
                    cerr << "bind failed: " << sqlite3_errmsg(db) << endl;
                } else {
                    rc = sqlite3_step(stmt);
                    if (rc != SQLITE_DONE)
                        cerr << "execution failed: " << sqlite3_errmsg(db) << endl;
                }
            }
            sqlite3_finalize(stmt);
        }
        sqlite3_close(db);
    
        delete[] buffer;
    }
    
    0 讨论(0)
提交回复
热议问题