Reputation: 97
I am writing an ODBC application in C! I have a table on my database and I'm going to fill it with some variables: Var1, Var2, ... which are the output of some function. The question is: in SQLExecDirect function, how should I pass to the SQL Statement (StatementText), the variables?
SQLExecDirect(hStmt, (SQLCHAR *)"INSERT INTO Table1 values (Var1, Var2, ...)", SQL_NTS);
Upvotes: 1
Views: 227
Reputation: 123578
You have two options:
sprintf
to build your SQL string as Paul Ogilvie shows in his answer;
Prepared statements can buy you some performance if you're repeating the same statement multiple times with different values (as shown at the link). They can also protect against SQL injection attacks (up to a point, anyway), but you should be sanitizing your inputs regardless. Tradeoff is that the prepared statement takes a little more coding effort.
Upvotes: 1
Reputation: 25286
In SQL in C, you create the full SQL statement by printing (formatting) it in a buffer. So if you want to insert the values of your variables into your table, you print their values to the buffer, like:
char szSQL[2048];
sprintf (szSQL, "INSERT INTO %s values('%s', %d,'%s');", szTableName, strVar1, intVar, strVar2);
SQLExecDirect(hStmt, szSQL, SQL_NTS);
Note the single quotes around the string variables and note there are no quotes around the integer variable. Note that that is the requirement of your TABLE, not of C. If the integer variable in your table is defined as a string field, then you must also place quotes around the variable in the SQL statement, '%d'
.
Finally, if the string variables can contain the single quote, then you must escape these as two single quotes.
Upvotes: 1