如何准备sql语句和绑定参数?

时间:2015-07-31 11:49:08

标签: c++ sqlite prepared-statement

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

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); PDO中所做的类似事情 - 使用命名参数准备语句并使用PHP标记。 / p>

2 个答案:

答案 0 :(得分:3)

您可以在此处找到相当数量的文档:sqlite.org
这个例子没有详细解释sqlite3函数调用和参数,因为这是很多要覆盖的信息 - 而是参考给定的链接以获得更深入的细节。

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

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

答案 1 :(得分:0)

据我所知http://hoogli.com/items/Avoid_sqlite3_clear_bindings().html,在这种情况下,步骤rc = sqlite3_clear_bindings( stmt );不是必需的。 不幸的是,我还没有被允许发布这个作为对前面非常好的答案的评论。