Commit 9167d7a4 authored by Soo Hyun Kim's avatar Soo Hyun Kim
Browse files

0704 db insert

parent b57c613d
......@@ -59,7 +59,7 @@ function App() {
}}>
<Tab.Screen name="Main" component={MainScreen} />
<Tab.Screen name="Monthly" component={Monthly} />
<Tab.Screen name="Analy" component={Analy} />
<Tab.Screen name="Analy" component={MoneyDB} />
</Tab.Navigator>
</NavigationContainer>
);
......
import SQLite from 'react-native-sqlite-storage';
import { View, Text, StyleSheet } from 'react-native';
import React, { useEffect } from 'react';
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';
SQLite.DEBUG(true);
SQLite.enablePromise(false);
DEBUG(true);
enablePromise(true);
const database_name = "MyMoney.db";
const database_version = "1.0"
const database_displayname = "SQLite Test Database";
const database_size = 200000;
let db;
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 loadAndQueryDB = () => {
db = SQLite.openDatabase(database_name, database_version, database_displayname, database_size, () => { console.log('load db') }, error => console.log(error.message));
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()
loadAndQueryDB();
return () => {
// closeDatabase(await db); // 컴포넌트 없어질 때 디비 닫기 Error!!!
};
}, []);
let listViewItemSeparator = () => {
return (
<View style={{ height: 0.2, width: '100%', backgroundColor: '#808080' }} />
);
};
}, [])
let listItemView = item => {
console.log('item in list view', item);
return (
<View>
<Text>Expense: {item.expense} Age: {item.income}</Text>
</View>
);
};
console.log('money', money);
console.log(expense, income)
return (
<>
<SafeAreaView>
<Text>db test</Text>
<View>
<Text style={style.Font}>-데이터 입력 테스트</Text>
<Text>expense</Text>
<TextInput
placeholder="expense"
onChangeText={
(expense) => setExpense(expense)
}
/>
<Text>income</Text>
<TextInput
placeholder="income"
onChangeText={
(income) => setIncome(income)
}
/>
<Button title='데이터 삽입하기' onPress={insertData} />
</View>
<View style={{ backgroundColor: 'gray' }}>
<Text style={style.Font}>-데이터</Text>
<View>
<Text>DB</Text>
<FlatList
data={money}
ItemSeparatorComponent={listViewItemSeparator}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => listItemView(item)}
/>
</View>
<Button title='데이터 다시 불러오기' onPress={loadAndQueryDB} />
</View>
</>
)
</SafeAreaView>
);
}
const style = StyleSheet.create({
Font: {
fontSize: 24
}
});
export default MoneyDB
\ No newline at end of file
......@@ -187,6 +187,7 @@ dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation project(':react-native-sqlite-storage')
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment