Expo SQLite如何插入一行并返回刚插入行的id

s2j5cfk0  于 2023-10-23  发布在  SQLite
关注(0)|答案(1)|浏览(153)

我创建了以下函数来将锻炼插入数据库。

const date = new Date().getDate();
  let id;

    await db.transaction( tx => {
          tx.executeSql( 'INSERT INTO workouts (name, created_at) values (?, ?)',
              [name, date]

              ,(transact,resultset) => {id = resultset.insertId, console.log('we made it', id )}
              ,(transact,err) => {console.log('We have encounter an Error', err)}

    );
    });

    //it does not return the id
    console.log("id before return" + id)
    return id;
}

我想返回刚插入的行的id,但它不起作用,返回undefined。但是行console.log('we made it',id)}确实正确地打印了id。该函数从以下代码调用:

const handleAddWorkoutModal = async (workoutName, setShowAddWorkoutModal, router) => {
  try {
    const id = database.insertWorkout(workoutName);
    console.log(id);
    setShowAddWorkoutModal(false);
    router.push({
      pathname: '/pages/workouts/createWorkout/CreateWorkout',
      params: { workoutName: workoutName, workoutId: id}
    });
  } catch (e) {
    console.warn(e);
  }
}
export default handleAddWorkoutModal;

我也试过使用SQLite的RETURNING语句,但它在ATM上有一些问题。
https://github.com/expo/expo/issues/24283
你能帮帮我吗?

hxzsmxv2

hxzsmxv21#

问题是我必须使用一个promise来让await正常工作。

const insertWorkout = (name) => {
  const date = new Date().getDate();
  let id;
    return new Promise((resolve, _reject) => {
        db.transaction( tx => {
                tx.executeSql('INSERT INTO workouts (name, created_at) values (?, ?)',
                    [name, date]
                    ,(transaction,resultSet) => {id = resultSet.insertId, console.log('we made it', id )}
                    ,(transaction,err) => {console.log('We have encounter an Error', err)}
                );
            },
            (t, error) => { console.log("db error inserting exercise"); console.log(error); resolve() },
            (t, success) => { resolve(id)}
        )
    })
}

.then用于获取插入中函数调用的值。

const handleAddWorkoutModal = async (workoutName, setShowAddWorkoutModal, router) => {
  let id;
  try {
    database.insertWorkout(workoutName).then(value => {
      console.log("id" + value);
      id = value;
    })
    setShowAddWorkoutModal(false);
    router.push({
      pathname: '/pages/workouts/createWorkout/CreateWorkout',
      params: { workoutName: workoutName, workoutId: id}
    });
  } catch (e) {
    console.warn(e);
  }
}

相关问题