代码之家  ›  专栏  ›  技术社区  ›  Program-Me-Rev

如何在C中的字符串中设置变量占位符

  •  0
  • Program-Me-Rev  · 技术社区  · 6 年前

    如何在C中的字符串中设置变量占位符?

    例如,设置 ID 来自变量 int id = 1234

    sql = "INSERT INTO REV_ENTITY (ID, NAME, AGE, ADDRESS, SALARY)" \
              "VALUES (99, 'John Doe', 25, 'Rich-Mond ', 65000.00 );";
    

    使现代化

    我想得到最后一个字符串,其中包含变量值。

    正如建议的那样,这不起作用:

    sql = "INSERT INTO REV_ENTITY (ID,NAME,AGE,ADDRESS,SALARY)" \  
        "VALUES (%d, 'REV', 25, 'Rich-Mond ', 65000.00 );";  
    
    rc = sqlite3_exec(db, printf(sql, 999), callback, 0, &zErrMsg);  
    

    我想要Java中的类似内容:

    String string = String.format("A string %s", aVariable);
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   medalib    6 年前

    此外 snprintf 在另一个答案中提到,您可以使用 char *sqlite3_mprintf(const char*,...) sqlite3 API中的函数。它使用sqlite printf 内置函数,并使用 sqlite3_malloc64() 。如果一切正常,则返回指向字符串的指针,否则返回 NULL :

    int id = 999;
    char *sql;
    sql = sqlite3_mprintf("INSERT INTO REV_ENTITY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (%d, 'REV', 25, 'Rich-Mond ', 65000.00 )", id);
    if (sql != NULL) {
        rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
        if (rc != SQLITE3_OK)
            /* Do some error handling. */
        sqlite3_free(sql);
    }
    

    不像 打印F 函数系列, sqlite3_mprintf 如果格式与参数不相关,则没有必要报告。因此,如果您使用GCC编译器,添加以下代码可能会很有用:

    extern char *sqlite3_mprintf(const char *format, ...) __attribute__ ((format (printf, 1, 2)));
    

    注释中推荐的另一种解决方案是使用sqlite3的prepare、step和finalize函数:

    int id = 999;
    sqlite3_stmt *stmt = NULL;
    char *sql = "INSERT INTO REV_ENTITY (ID,NAME,AGE,ADDRESS,SALARY) " \
                " VALUES (?, 'REV', 25, 'Rich-Mond ', 65000.00 )";
    sqlite3_prepare(db, sql, strlen(sql), &stmt, NULL);
    /* Bind id. */
    sqlite3_bind_int(stmt, 1, id);
    if (sqlite3_step(stmt) == SQLITE_DONE) {
        printf("Insertion success\n");
    } else {
        fprintf(stderr, "Insertion error\n");
    }
    /* Finalize and destroy statement. */
    sqlite3_finalize(stmt);
    
        2
  •  -1
  •   bestestefan    6 年前

    使用 snprintf ,伪代码如下所示:

    int idValue = 1234;
    snprintf(buffer, bufferLength, "insert bla bla VALUES (%d, 'John Doe', 25, 'Rich-Mond ', 65000.00 )", idValue);
    sqli_execute(buffer);
    

    在您的情况下,它将如下所示:

    //initialize sql variable before sprintfing into it
    snprintf(sql, maximumSqlBufferLength "INSERT INTO REV_ENTITY (ID, NAME, AGE, ADDRESS, SALARY) VALUES (%d, 'John Doe', 25, 'Rich-Mond ', 65000.00 );", id);