gpt4 book ai didi

c++ - 如何编写sql语句和绑定(bind)参数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:41 26 4
gpt4 key购买 nike

不幸的是,documentation完全没有例子(真的很奇怪),好像它假定所有读者都是优秀的程序员。然而,我是 C++ 的新手,无法从文档中真正弄清楚如何真正准备和执行语句。我喜欢它在 PDO for PHP 中的实现方式。通常,我只是这样做:

$s = $db->prepare("SELECT id FROM mytable WHERE id = :id");
$s->bindParam(':id', $id);
$s->execute();

还是使用 ? 标记:

 $data = array();
$data[] = 1;
$data[] = 2;
$s = $db->prepare("SELECT id FROM mytable WHERE id = ? or id = ?");
$s->execute($data);

现在,我手头有C++sqlite3.h。此时此刻,我知道如何连接到数据库——我这样做并且没有出现错误:

sqlite3 * conn;
int rc = sqlite3_open(db_name, &conn);

请给出一些关于如何实现 PDOPHP 中所做的类似事情的说明(带有清晰的小示例) - 使用命名参数准备语句并使用 ? 标记。

最佳答案

您可以在此处找到大量文档:sqlite.org
此示例未详细解释 sqlite3 函数调用和参数,因为要涵盖的信息相当多 - 请参阅给定链接以获取更深入的详细信息。

此示例多次将值绑定(bind)到问题中的语句,并在每次绑定(bind)后读取所有查询结果:

sqlite3* conn;
sqlite3_stmt* stmt = 0;

int rc = sqlite3_open(db_name, &conn);
// Good idea to always check the return value of sqlite3 function calls.
// Only done once in this example:
if ( rc != SQLITE_OK ) { // Do something }

rc = sqlite3_prepare_v2( conn, "SELECT id FROM myTable WHERE id = ? or id = ?", -1, &stmt, 0 );

// Optional, but will most likely increase performance.
rc = sqlite3_exec( conn, "BEGIN TRANSACTION", 0, 0, 0 );

for ( int bindIndex = 0; bindIndex < number_of_times_you_wish_to_bind; bindIndex++ ) {
// Binding integer values in this example.
// Bind functions for other data-types are available - see end of post.

// Bind-parameter indexing is 1-based.
rc = sqlite3_bind_int( stmt, 1, int_you_wish_to_bind ); // Bind first parameter.
rc = sqlite3_bind_int( stmt, 2, int_you_wish_to_bind ); // Bind second parameter.

// Reading interger results in this example.
// Read functions for other data-types are available - see end of post.
while ( sqlite3_step( stmt ) == SQLITE_ROW ) { // While query has result-rows.
// In your example the column count will be 1.
for ( int colIndex = 0; colIndex < sqlite3_column_count( stmt ); colIndex++ ) {
int result = sqlite3_column_int( stmt, colIndex );
// Do something with the result.
}
}
// Step, Clear and Reset the statement after each bind.
rc = sqlite3_step( stmt );
rc = sqlite3_clear_bindings( stmt );
rc = sqlite3_reset( stmt );
}
char *zErrMsg = 0; // Can perhaps display the error message if rc != SQLITE_OK.
rc = sqlite3_exec( conn, "END TRANSACTION", 0, 0, &zErrMsg ); // End the transaction.

rc = sqlite3_finalize( stmt ); // Finalize the prepared statement.

More Bind Functions

More Read Functions

关于c++ - 如何编写sql语句和绑定(bind)参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31745465/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com