Search code examples
databasereact-nativesql-inserttextinput

Unable to insert data to database using textinput value


I want to insert data retrieved from textinput and store it into database table.

I tried passing the textinput value as this.state.text1,but it does not insert and no action is perfomed

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);

 }

Expected result:The textinput value should be inserted to the table inside database

Actual result:No value is inserted to database.It shows NULL in the database when queried.


Solution

  • Change Your Query as

    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);
    
    }