【问题标题】:Clearing bindings on an SQLite3 statement doesn't seem to work (PHP)清除 SQLite3 语句上的绑定似乎不起作用(PHP)
【发布时间】:2015-12-31 06:59:22
【问题描述】:

当使用准备好的语句在 PHP 中向 SQLite3 插入多行时,如果您没有为一行绑定参数,那么即使您“清除”行之间的语句,也会插入前一行的值。

看下面的例子:

$db = new SQLite3('dogsDb.sqlite');

//create the database
$db->exec("CREATE TABLE Dogs (Id INTEGER PRIMARY KEY, Breed TEXT, Name TEXT, Age INTEGER)");    

$sth = $db->prepare("INSERT INTO Dogs (Breed, Name, Age)  VALUES (:breed,:name,:age)");

$sth->bindValue(':breed', 'canis', SQLITE3_TEXT);
$sth->bindValue(':name', 'jack', SQLITE3_TEXT);
$sth->bindValue(':age', 7, SQLITE3_INTEGER);
$sth->execute();

$sth->clear(); //this is supposed to clear bindings!
$sth->reset();

$sth->bindValue(':breed', 'russel', SQLITE3_TEXT);         
$sth->bindValue(':age', 3, SQLITE3_INTEGER);
$sth->execute();

尽管我希望第二行的 'name' 列具有 NULL 值,但该值是 'jack'!

所以要么“清除”似乎不起作用(尽管它返回 true),要么我还没有真正理解它应该做什么。

如何清除 SQLite3(甚至 PDO)中插入之间的绑定?在某些行的某些字段可能具有空值的情况下插入多行的最佳方法是什么?

【问题讨论】:

标签: php sqlite prepared-statement prepare


【解决方案1】:
#include <sqlite3.h>
#include <stdio.h>

int main(void) {

    sqlite3 *db;
    char *err_msg = 0;
    sqlite3_stmt *res;
    sqlite3_stmt *res1;
    int rc = sqlite3_open("test.sqlite", &db);

    if (rc != SQLITE_OK) {

        fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);

        return 1;
    }

    char *sql = "CREATE TABLE Dogs (Id INTEGER PRIMARY KEY, Breed TEXT, Name TEXT, Age TEXT)";
    rc = sqlite3_prepare_v2(db, sql, -1, &res, 0);
    if (rc == SQLITE_OK) {
        rc = sqlite3_step(res);

    }
    sqlite3_finalize(res);

    char *sql1 = "INSERT INTO Dogs (Breed, Name, Age)  VALUES (:breed,:name,:age);";

    rc = sqlite3_prepare_v2(db, sql1, -1, &res1, 0);


    if (rc == SQLITE_OK) {
        printf("%d\n", sqlite3_bind_text(res1, 1, "breed1", 6, SQLITE_STATIC));
        sqlite3_bind_text(res1, 2, "name1", 5, SQLITE_STATIC);
        sqlite3_bind_text(res1, 3, "age1", 4, SQLITE_STATIC);
        printf("%d\n", sqlite3_step(res1));
    } else {

        fprintf(stderr, "Failed to execute statement: %s\n", sqlite3_errmsg(db));
    }
    sqlite3_reset(res1);
    sqlite3_clear_bindings(res1);
    printf("%d\n", sqlite3_bind_text(res1, 2, "name2", 5, SQLITE_STATIC));
    printf("%d\n", sqlite3_bind_text(res1, 3, "age2", 4, SQLITE_STATIC));

    printf("%d\n", sqlite3_step(res1));


    sqlite3_finalize(res1);
    sqlite3_close(db);

    return 0;
}

【讨论】:

  • 感谢您的回复。如果等效代码在 C 中有效,则意味着 可能 这是一个 PHP 错误。但是我不确定它与您链接到的其他错误有关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多