React Native Expo SQLite事务中INSERT语句未执行问题求助
问题原因与解决方案
核心问题是Expo SQLite的executeSql方法默认不支持在单个调用中执行多条SQL语句。你把CREATE TABLE和INSERT写在同一个executeSql里,虽然建表语句能正常执行,但插入语句会被静默忽略——因为整体语法没有错误,所以不会触发错误回调,但实际并未执行插入操作。
解决方法
将两条SQL语句拆分,分别调用tx.executeSql,同时建议使用参数占位符?替代直接变量拼接(更安全,避免SQL注入风险):
database.transaction(tx => { // 第一步:执行建表语句 tx.executeSql( `CREATE TABLE IF NOT EXISTS ${TABLE_NAMES.Metadata} ( theme TEXT CHECK( theme IN ('dark', 'light') ), tutorialCompleteDate INTEGER, userEmail TEXT, lastPaymentDate INTEGER, lastExportDate INTEGER, lastUseDate INTEGER );`, [], // 建表成功后执行插入 () => { tx.executeSql( `INSERT INTO ${TABLE_NAMES.Metadata} (theme, tutorialCompleteDate, userEmail, lastExportDate, lastUseDate) VALUES (?, ?, ?, ?, ?);`, ['dark', null, null, null, new Date().getTime()], (_, result) => resolve(result), (_, error) => { console.log(error); reject(error); return true; } ); }, (_, error) => { console.log(error); reject(error); return true; } ); });
补充说明
- 故意写错INSERT语句时,整个SQL块语法出错,所以会触发错误回调;而合法的多语句只是不被Expo SQLite的
executeSql支持,不会报错但后续语句不执行。 - 使用
?占位符传递参数是SQLite的最佳实践,能避免直接拼接字符串带来的安全风险和格式问题。
内容的提问来源于stack exchange,提问作者rook218
相关产品推荐
相关产品推荐

