How to insert any row in sqlite3 in c

I need to insert a row into my sqlite database command ..

Err=sqlite_exec(DB, "create table tbl5(TEXT varchar(100));", xCallback, (void*)"First Test", &ErrMsg); Err=sqlite_exec(DB, "insert into tbl5 values ('some string');", xCallback, (void*)"First Test", &ErrMsg); 

works fine, but when I want to put s="some string" ie

 Err=sqlite_exec(DB, "insert into tbl5 values (s);", xCallback, (void*)"First Test", &ErrMsg); 

then this does not work, since adding a variable, then it does not work, since inserting a variable into sqlite database thanks u

+4
source share
3 answers

Do not use sprintf() , but sqlite3_mprintf() . Here is the documentation.

 char s[20] = "some string"; char* query = sqlite3_mprintf("insert into tbl5 values ('%q');", s); 

Otherwise, you risk SQL injection .

The resulting query string should be freed using sqlite3_free() .

Also pay attention to '%q' instead of the usual '%s' .

+6
source

In addition to the suggested sentences, you can also use prepared statements with bound parameters (this is also useful if you intend to repeat the instruction several times with different parameters). see sqlite3_prepare_v2 and sqlite3_bind_* for more information

 sqlite3_stmt *stmt; // Create a prepared statement. Err = sqlite3_prepare_v2(DB, "insert into tbl5 values (?)", -1, &stmt, NULL); if (Err != SQLITE_OK) { //... } // Bind our string to the statement. Err = sqlite3_bind_text(stmt, 1, "some string", -1, SQLITE_TRANSIENT); if (Err != SQLITE_OK) { //... } // Execute the statement. Err = sqlite3_step(stmt); if (Err != SQLITE_DONE) { //... } // Free the prepared statement. Err = sqlite3_finalize(stmt); 
+2
source

You can use sprintf to create a formatted string.

 char s[20] = "some string"; char query[100]; sprintf(query, "insert into tbl5 values (%s);", s); 

You need to make sure the query is big enough.

0
source

Source: https://habr.com/ru/post/1311394/


All Articles