【问题标题】:Unable to insert data to database using textinput value无法使用文本输入值将数据插入数据库
【发布时间】:2019-08-05 12:01:19
【问题描述】:

我想插入从 textinput 检索到的数据并将其存储到数据库表中。

我尝试将 textinput 值作为 this.state.text1 传递,但它没有插入,也没有执行任何操作

sync (){
   console.log('inside sync function');
  const { value1 } = this.state.text1;
    console.log('value1 is' +this.state.text1 );
   db.transaction(function(txn) {
    txn.executeSql(
      "INSERT INTO " +
        localDB.tableName.tblLogin +
        " (text1,text2) VALUES (:text1,:text2)",
      [
         +this.state.text1,
        "native3"
      ]
    );
  });
  console.log('insert values success');
  console.log(this.state.text1);
  console.log(this.state.text2);

 }

预期结果:文本输入值应该插入到数据库内的表中

实际结果:数据库中没有插入值,查询时显示为NULL。

【问题讨论】:

  • 你的控制台结果是什么。即console.log('value1 is' +this.state.text1 ) .. 控制台中有什么
  • 我得到了正确的文本输入值,但是当它在查询中插入时,它在表中给出了 NULL
  • 您确定查询字符串的解释正确吗?尝试对查询字符串进行硬编码。那么数据库是否添加了值?
  • 是的,当硬编码时它正在取值
  • 试试这个,把你的查询字符串放在一个字符串模板变量中,像这样,让 query = INSERT INTO ${localDB.tableName.tblLogin} ..etc. (确保使用波浪号)然后打印到控制台。比较两个字符串、有效的硬编码和准备好的查询变量。有时数据库需要“INSERT INTO `table_name'..”而不是“INSERT INTO table_name”

标签: database react-native sql-insert textinput


【解决方案1】:

将您的查询更改为

async sync  = () => {

  console.log('inside sync function');
  console.log('text1 is' + this.state.text1 );

  await db.transaction((txn) => {

    txn.executeSql(
        `INSERT INTO ${localDB.tableName.tblLogin}(text1,text2) VALUES (?,?)`,
        [this.state.text1,"native3"], 
        (r) => {console.log("success" , r);},
        (error) => {console.log("error is", error);}
    );

 });

  console.log('insert values success');
  console.log(this.state.text1);

}

【讨论】:

  • 我试过了,但没有行添加到表中,也没有错误
  • 更新了我的答案,请告诉相应的控制台消息。
  • 它没有进入任何成功或错误控制台。这个变量r没有任何作用
  • 请尝试更新提供的同步功能。你的所有控制台结果是什么
【解决方案2】:

尝试使用 setTimeout(() => 将插入延迟 1 秒。 React 的 this.setState 不是即时的。

sync (){
   console.log('inside sync function');
  const { value1 } = this.state.text1;
    console.log('value1 is' +this.state.text1 );

   setTimeout(() => {
       db.transaction(function(txn) {
       txn.executeSql(
         "INSERT INTO " +
           localDB.tableName.tblLogin +
           " (text1,text2) VALUES (:text1,:text2)",
         [
            +this.state.text1,
           "native3"
         ]
        );
       });
   }, 1000);

  console.log('insert values success');
  console.log(this.state.text1);
  console.log(this.state.text2);

 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多