【问题标题】:Insert multiple records in Sqlite using React Native使用 React Native 在 Sqlite 中插入多条记录
【发布时间】:2020-03-01 19:53:51
【问题描述】:

我尝试使用 SQLite 在 React Native 中插入多行。

这是代码:

rows = responseJson.rows;

     for (i = 0; i < rows.length; i++) {

        row=rows[i];
        query = `insert into ComuniUserAccountSync values (
            ${row.IDComuniUserAccountSync},
            ${row.IdAzienda},
            ${row.IdComune},
            ${row.IdUserAccount},
            '${row.DescrizioneComune}',
            '${row.DateLastUpdateMaster}'
        )`;


        db.transaction(
            tx => {
                tx.executeSql(query, [], (a,b) =>
                    console.log("!OK!!", JSON.stringify(b)), (a, b) =>
                        console.log("!ERROR!!", a, b)
                )

            }
       );

     }

但结果是我多次只插入最后一行!这是

的输出
db.transaction(
        tx => {
            tx.executeSql("select IDComuniUserAccountSync from ComuniUserAccountSync", [], (a,b) =>
            console.log("!OK!", JSON.stringify(b)), (a,b) =>
            console.log("!ERROR!!", JSON.stringify(b))
    );
        }
    );

!好的! {"rowsAffected":0,"rows":{"_array":[{"IDComuniUserAccountSync":72},{"IDComuniUserAccountSync":72},{"IDComuniUserAccountSync":72},{"IDComuniUserAccountSync":72},{ "IDComuniUserAccountSync":72}, .......

有什么帮助吗?? 最大

【问题讨论】:

  • 您是否尝试在循环中使用 async/await 来确保执行所有查询??

标签: sqlite react-native expo


【解决方案1】:
insertCategories(arrCateData){


  let keys = Object.keys(arrCateData[0])

  let arrValues = []

    var len = arrCateData.length;



    for (let i = 0; i < len; i++) {
      arrCateData[i].image = `"${arrCateData[i].image}"`;
      arrCateData[i].thumbnail = `"${arrCateData[i].thumbnail}"`;
      arrCateData[i].name = `"${arrCateData[i].name}"`;
      arrCateData[i].path = `"${arrCateData[i].path}"`;
      arrValues.push("(" + Object.values(arrCateData[i]) +")");
    }

    // console.log(arrValues)


  return new Promise((resolve) => {
    this.initDB().then((db) => {
      db.transaction((tx) => {
        tx.executeSql("INSERT INTO category ("+ keys + ") VALUES " + String(arrValues)).then(([tx, results]) => {
          resolve(results);
        });
      }).then((result) => {
        this.closeDatabase(db);
      }).catch((err) => {
        console.log(err);
      });
    }).catch((err) => {
      console.log(err);
    });
  });  

}

这段代码可以帮助你,我只是将我的数组传递给函数,它会根据你的要求插入数据 jusr 更改数据

【讨论】:

  • 我对 sqlite 有一些问题,我创建了 insert fetch delete 函数,但由于某种原因它对我不起作用。你能帮我吗?
猜你喜欢
  • 2021-01-06
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多