在react-native-sqlite-storage的测试中(请参阅https://github.com/andpor/react-native-sqlite-storage/blob/master/test/index.ios.promise.js#L141-L149),我发现:
tx.executeSql('INSERT INTO Employees (name, office, department) VALUES ("Sylvester Stallone", 2, 4);');
tx.executeSql('INSERT INTO Employees (name, office, department) VALUES ("Elvis Presley", 2, 4);');
tx.executeSql('INSERT INTO Employees (name, office, department) VALUES ("Leslie Nelson", 3, 4);');
tx.executeSql('INSERT INTO Employees (name, office, department) VALUES ("Fidel Castro", 3, 3);');
tx.executeSql('INSERT INTO Employees (name, office, department) VALUES ("Bill Clinton", 1, 3);');
tx.executeSql('INSERT INTO Employees (name, office, department) VALUES ("Margaret Thatcher", 1, 3);');
tx.executeSql('INSERT INTO Employees (name, office, department) VALUES ("Donald Trump", 1, 3);');
tx.executeSql('INSERT INTO Employees (name, office, department) VALUES ("Dr DRE", 2, 2);');
tx.executeSql('INSERT INTO Employees (name, office, department) VALUES ("Samantha Fox", 2, 1);');
有没有一种方法可以通过传递一个数组来处理一个语句?
答案 0 :(得分:0)
这不是一个单一的命令,但是我认为有一种减少代码的方法。安排命令语句并使用map函数重复事务。
示例
const txArray = ['INSERT INTO Employees (name, office, department) VALUES ("Sylvester Stallone", 2, 4);','INSERT INTO Employees (name, office, department) VALUES ("Elvis Presley", 2, 4);', ....]
...
txArray.map((tx, i) => { tx.executeSql(tx); console.log(i + ': success') }
答案 1 :(得分:0)
假设myDb是您的连接变量:
const myDb=SQLite.openDatabase({name:"yourDb", createFromLocation:"yourDB.db"}, ()=>console.log('DB opened'), (err)=>alert('error : ' + err));
如果您想在“雇员”表中插入三行:
myDb.transaction((tx)=>{
tx.executeSql(
'INSERT INTO Employees (name,office,departement) VALUES (?,?,?),(?,?,?),(?,?,?)',
['Sylvester Stallone',2,4,'Elvis Presley',2,4,'Leslie Nelson',3,4],
(tx, results) => {
if (results.rowsAffected > 0 ) {
console.log('Insert success');
} else {
console.log('Insert failed');
}
}
);
});
祝你好运!