首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法使用sqlite3_bind_text插入到数据库中

无法使用sqlite3_bind_text插入到数据库中
EN

Stack Overflow用户
提问于 2019-03-18 17:46:40
回答 1查看 526关注 0票数 1

你好,我有一个关于这个函数recup()的问题。recup()的目的是将字符串chaine中的所有单词逐个插入到数据库中。这些单词来自用户使用fgets设置的chaine。我面临的问题是,它只插入与chaine的第一个单词具有相同长度的单词。例如,如果我写"I want a cat",则只会插入"I“和"a”。

代码语言:javascript
复制
int recup(char *chaine){

    char tab[30] ={0};
    char delim[] = " ";
    char *ptr = strtok(chaine,delim);

    int rc =0;
    char *sql ="INSERT INTO newTable SELECT * FROM dbTable where lemme =?";

    sqlite3_stmt *stmt = 0;

    rc = sqlite3_prepare_v2(db,sql,-1,&stmt,0); 

    do {
        // Expected word is printed here
        printf("%s\n",ptr);
        strcpy(tab,ptr);

        // For some reason, only words that match the length
        // of the first word are being inserted
        rc = sqlite3_bind_text(stmt,1,tab,-1,SQLITE_STATIC);  
        rc = sqlite3_step(stmt);
        ptr = strtok(NULL,delim);
    } while(ptr != NULL);
    rc = sqlite3_finalize(stmt); 
    return 0;
}


#include <ansi_c.h>
#include <sqlite3.h>
#include "fdata.h"
sqlite3 *db;   

int main(int argc, char* argv[]) { 
      int rc = 0;
      char chaine[100] = {0};
      rc = sqlite3_open("lexique.db",&db);
      check(rc);
      createNewT();
      question(&chaine);
      recup(&chaine);
      sqlite3_close(db); 
      return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2019-03-18 19:06:10

函数的作用是:修改传入的字符串。因此,有必要创建输入字符串的副本。请参阅@David Cullen的优秀答案,它创建了一个mcve。

请参阅已更正代码中的注释,这些注释解释了正在发生的情况。

代码语言:javascript
复制
#include <stdio.h>
#include <string.h>

int recup(char *chaine){


  char tab[30] ={0};
  char delim[] = " ";
  ///// strtok will modify its inut string argument, so create a copy of the input
  strcpy(tab, chaine);
  // ptr will contain the current last token that was parsed
  char *ptr = strtok(tab,delim); // pass the copy to strtok, ptr points to first word

  int rc =0;
  char *sql ="INSERT INTO newTable SELECT * FROM dbTable where lemme =?";

  sqlite3_stmt *stmt = 0;

  rc = sqlite3_prepare_v2(db,sql,-1,&stmt,0);


  while (ptr) {
    printf("%s\n",ptr);  // print the word that was just tokenized

    rc = sqlite3_bind_text(stmt,1,ptr,-1,SQLITE_STATIC);
    rc = sqlite3_step(stmt);
    ptr = strtok(NULL,delim);
  }
  rc = sqlite3_finalize(stmt);
  return 0;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55218499

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档