简体   繁体   中英

SQL Statement in ODBC

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);

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.

You have two options:

  1. You can use sprintf to build your SQL string as Paul Ogilvie shows in his answer;
  2. You can use a prepared statement and bind the variables to it in a separate operation (see example at link).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM