【问题标题】:sqlite c api insert bindingsqlite c api插入绑定
【发布时间】:2014-12-09 11:19:35
【问题描述】:

我正在尝试使用 sqlite3_bind_* 函数调用在 sqlite DB 中插入值。

这是我正在使用的代码:

#include <stdio.h>
#include "sqlite3.h"
#include <stdlib.h>
#include <string.h>

static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
    int i;
    printf("\n callback");
    for (i = 0; i < argc; i++) {
        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
    printf("\n");
    return 0;
}

int main() {

   int rc;
   char *pStrSql,*zErrMsg;
   sqlite3 *db;
   sqlite3_stmt *pInsertStmt;

   int iAge;
   char *pStrName;
   const char *pStrInsSql;

   const char **pzTail;


    rc = sqlite3_open("test.db", &db);
    if (rc) {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        exit(0);
    } else {
        fprintf(stdout, "Opened database successfully\n");
    }



    pStrSql = "DROP TABLE employee";
    rc = sqlite3_exec(db, pStrSql, callback, 0, &zErrMsg);

    pStrSql = "CREATE TABLE employee (name text,age int);";

    rc = sqlite3_exec(db, pStrSql, callback, 0, &zErrMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    } else {
       printf("Table created successfully\n");
    }


    pStrInsSql = "INSERT INTO employee VALUES (?,?)";

    rc = sqlite3_prepare_v2(db,pStrInsSql,-1,&pInsertStmt,NULL);
    if( rc != SQLITE_OK) {
        printf("\n Cant prepare Error %s :",sqlite3_errmsg(db));
        exit(0);
    }

    pStrName = "prakash";
    rc = sqlite3_bind_text(pInsertStmt,1,pStrName,-1,SQLITE_TRANSIENT);
     if( rc != SQLITE_OK) {
        printf("\n Cant bind text Error %s :",sqlite3_errmsg(db));
        exit(0);
    }
    iAge = 23;
    rc = sqlite3_bind_int(pInsertStmt,2,iAge);
     if( rc != SQLITE_OK) {
        printf("\n Cant bind int Error %s :",sqlite3_errmsg(db));
        exit(0);
    }

    rc = sqlite3_step(pInsertStmt);
    if( rc != SQLITE_OK) {
        printf("\n Cant execute insert Error %s :",sqlite3_errmsg(db));
        exit(0);
    }

    sqlite3_clear_bindings(pInsertStmt);
    sqlite3_reset(pInsertStmt);
    sqlite3_finalize(pInsertStmt);

    pStrSql = "select * from employee";

    rc = sqlite3_exec(db, pStrSql, callback, 0, &zErrMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    } 

    sqlite3_close(db);

    return 0;
}

调用 sqlite3_step() 后程序失败。 错误消息是“未知错误”。

你能帮我解决这个问题吗? 谢谢 普拉卡什

【问题讨论】:

    标签: c sqlite binding sql-insert


    【解决方案1】:

    sqlite3_step() 成功时不返回 SQLITE_OK;您必须检查 SQLITE_DONE(和 SQLITE_ROW 查询)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-19
      • 2011-06-06
      • 1970-01-01
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      相关资源
      最近更新 更多