import { DEBUG, enablePromise, openDatabase } from 'react-native-sqlite-storage';
import { SafeAreaView, StyleSheet, Text, View, TextInput, FlatList, Button } from 'react-native';
import React, { useEffect, useState } from 'react';
DEBUG(true);
enablePromise(true);
const db = openDatabase({
name: 'MyMoney',
location: 'default',
createFromLocation: '~MyMoney.db', // android/src/main/assets/TestDB.db 파일을 위치 시킴
});
function MoneyDB() {
const [money, setMoney] = useState([]);
const [expense, setExpense] = useState(0)
const [income, setIncome] = useState(0)
console.log('money db')
const populateDatabase = async DB => {
await DB.transaction(queryMoney); // 반드시 (await db)를 해야 프라미스가 성공
};
const loadAndQueryDB = async () => {
try {
console.log('load and db query ....');
await populateDatabase(await db);
} catch (error) {
console.log(error);
}
};
const closeDatabase = async DB => {
if (DB) {
console.log('closing database ...');
try {
(await DB).close(
() => {
console.log('Database was closed successfully');
},
err => console.log(err),
);
} catch (error) {
console.log(error);
}
} else {
console.log('Database was not opened');
}
};
const queryMoney = async tx => {
console.log('Excuting user query');
try {
const [txn, results] = await tx.executeSql('SELECT * FROM Money');
console.log('item length', results.rows.length);
const temp = [];
for (let i = 0; i < results.rows.length; i++) {
const element = results.rows.item(i);
temp.push(element);
console.log('item ', element);
}
setMoney(temp);
} catch (error) {
console.log('error in query money', error);
}
};
const insertData = async () => {
try {
(await db).transaction((tx) => {
console.log("데이터 삽입하기");
tx.executeSql('INSERT INTO Money (expense, income) VALUES (?,?);',
[expense, income],
() => { console.log("삽입 성공"); },
(error) => console.log(error))
})
} catch (error) {
console.log('error in insert data', error)
}
}
//수정 전 코드
// const insertData = async () => {
// await db.transaction(async (tx) => {
// console.log("데이터 삽입하기");
// tx.executeSql('INSERT INTO Money (expense, income) VALUES (?,?);',
// [expense, income],
// () => { console.log("삽입 성공"); },
// (error) => console.log(error))
// })
// }
useEffect(() => {
loadAndQueryDB();
return () => {
// closeDatabase(await db); // 컴포넌트 없어질 때 디비 닫기 Error!!!
};
}, []);
let listViewItemSeparator = () => {
return (
);
};
let listItemView = item => {
console.log('item in list view', item);
return (
Expense: {item.expense} Age: {item.income}
);
};
console.log('money', money);
console.log(expense, income)
return (
db test
-데이터 입력 테스트
expense
setExpense(expense)
}
/>
income
setIncome(income)
}
/>
-데이터
index.toString()}
renderItem={({ item }) => listItemView(item)}
/>
);
}
const style = StyleSheet.create({
Font: {
fontSize: 24
}
});
export default MoneyDB