介绍
我正在尝试使用 C 将变量合并到查询中。我正在使用 sqlite tutorialspoint 学习本教程,并且我第一次接触到使用 SQL。本教程向我展示了如何使用查询,例如:
询问
sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; " \
"SELECT * from COMPANY";
Run Code Online (Sandbox Code Playgroud)
*那么我将如何将变量合并到此语句中,例如,如果我想用分配给“ID”的变量替换 1。
例如(我失败的尝试)
sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=" + variable + ";" \
"SELECT * from COMPANY";
Run Code Online (Sandbox Code Playgroud)
我在谷歌上搜索过,但是我真的找不到任何关于使用 C 语言语法在 sql 查询中使用变量的材料。我将如何以正确和安全的方式解决这个问题,以合并变量而不使程序容易受到 SQL 注入的影响?
C-API 提供了函数sqlite3_prepare_v2,sqlite3_bind以便您可以将参数绑定到准备好的语句。这意味着,您可以使用占位符来替换字符串中的参数。
每个占位符都由一个索引引用,因此您可以使用任意数量的参数(最多可达 SQLITE_MAX_VARIABLE_NUMBER 设置的编译时间限制)。然后将参数绑定到指定索引处的占位符。
有许多函数和方法可以完成参数替换,但为了让您入门,这里有一个将整数绑定到 sql 语句中的第一个占位符的示例:
int rc;
sqlite3 *db;
sqlite3_stmt *stmt = NULL;
...
// here I assume you open the db, and provide any other working code as needed...
...
// the employee id number.
int id_num;
...
// create the sql statement, with a single placeholder marked by '?'.
char *sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=?";
// prepare the sql statement.
rc = sqlite3_prepare_v2(db, sql, strlen(sql)+1, &stmt, NULL);
if (rc != SQLITE_OK) {
printf("Failed to prepare statement: %s\n\r", sqlite3_errstr(rc));
sqlite3_close(db);
return 1;
}
else {
printf("SQL statement prepared: OK\n\n\r");
}
// bind an integer to the parameter placeholder.
rc = sqlite3_bind_int(stmt, 1, id_num);
if (rc != SQLITE_OK) {
printf("Failed to bind parameter: %s\n\r", sqlite3_errstr(rc));
sqlite3_close(db);
return 1;
}
else {
printf("SQL bind integer param: OK\n\n\r");
}
// evaluate the prepared statement.
rc = sqlite3_step(stmt);
// other successful return codes are possible...
if (rc != SQLITE_DONE) {
printf("Failed to execute statement: %s\n\r", sqlite3_errstr(rc));
sqlite3_close(db);
return 1;
}
// deallocate/finalize the prepared statement when you no longer need it.
// you may also place this in any error handling sections.
sqlite3_finalize(stmt);
...
// close the db when finished.
sqlite3_close(db)
...
// finish your code.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2040 次 |
| 最近记录: |