sqlite - C - How to use variables as part of an SQL Query? -




introduction

i'm attempting incorporate variables queries using c. i'm following tutorial using sqlite tutorialspoint , , first exposure using sql. tutorial has shown me how use queries such these:

query

sql = "update company set salary = 25000.00 id=1; " \      "select * company"; 

*so how go incorporating variables statement, example if wanted replace 1 variable assigned 'id'.

for example(my failed attempt)

sql = "update company set salary = 25000.00 id=" + variable + ";" \      "select * company"; 

i've googling around couldn't find material on using variables in sql queries using c language syntax. how go in correct , safe way, incorporate variables , without making program vulnereable sql injection?

the c-api provides functions sqlite3_prepare_v2 , sqlite3_bind can bind parameters prepared statements. means is, can use placeholder want substitute parameters within string.

each placeholder referenced index, can use many parameters (up compile-time limit set sqlite_max_variable_number). bind parameter placeholder @ specified index.

there number of functions , methods accomplish parameter substitution, started, here's example binds integer 1st placeholder in sql statement:

int rc; sqlite3 *db; sqlite3_stmt *stmt = null; ... // here assume open db, , provide other working code needed... ... // employee id number. int id_num; ...  // create sql statement, single placeholder marked '?'. char *sql = "update company set salary = 25000.00 id=?";  // prepare sql statement. rc = sqlite3_prepare_v2(db, sql, strlen(sql)+1, &stmt, null); if (rc != sqlite_ok) {     printf("failed prepare statement: %s\n\r", sqlite3_errstr(rc));     sqlite3_close(db);     return 1; }  else {     printf("sql statement prepared: ok\n\n\r"); }  // bind integer parameter placeholder.  rc = sqlite3_bind_int(stmt, 1, id_num); if (rc != sqlite_ok) {     printf("failed bind parameter: %s\n\r", sqlite3_errstr(rc));     sqlite3_close(db);     return 1; }  else {     printf("sql bind integer param: ok\n\n\r"); }  // evaluate prepared statement. rc = sqlite3_step(stmt); // other successful return codes possible... if (rc != sqlite_done) {     printf("failed execute statement: %s\n\r", sqlite3_errstr(rc));     sqlite3_close(db);     return 1; }  // deallocate/finalize prepared statement when no longer need it. // may place in error handling sections. sqlite3_finalize(stmt);  ... // close db when finished. sqlite3_close(db) ... // finish code. 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -