Wakkun
Wakkun

Reputation: 41

C++ SQLite cannot convert `std::basic_string<char, std::char_traits<char>, std::allocator<char> >' to `char*' in assignment

I'm trying to use C++ and SQLite but I don'tknow how to pass the parameters into a single string to form the SQLite command.

void InsertDB(unsigned long long phone,string name,int age,string address,long int zipcode)
{
stringstream insert;
insert << "INSERT INTO ADBOOK (PHONE,NAME,AGE,ADDRESS,ZIPCODE) VALUES (" << phone << ",'" << name << "'," << age << ",'" << address << "'," << zipcode << " ); ";
sql = insert.str();

/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}else{
fprintf(stdout, "Records created successfully\n");
}
return;     

}

I keep getting an error error: cannot convert std::basic_string<char, std::char_traits<char>, std::allocator<char> >' tochar*' in assignment

How can I make this block of code work?

Is there any easier way to implement this? This is a project which requires C++ and any kind of database (MySQL,etc.)

Ok so here's the full code, this is a college project and I really need a bit of help to solve this http://pastebin.com/XiisxBxf

Upvotes: 2

Views: 3055

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254501

You can use the c_str() member function of std::string to get a pointer to a zero-terminated character sequence, suitable for passing to C-style functions:

rc = sqlite3_exec(db, sql.c_str(), callback, 0, &zErrMsg);
                         ^^^^^^^^

By the way, what happens if I give my name as "); DROP TABLE ADBOOK #"? Never insert user-provided strings directly into queries; prepare a statement with placeholders to bind to the input.

Also, round my way, neither phone numbers nor post/zipcodes can be represented by integers.

Upvotes: 2

Related Questions