test database

This commit is contained in:
CalebChen768 2024-03-19 00:00:35 +08:00
parent 67a4f27b8d
commit f13166f490
2 changed files with 194 additions and 0 deletions

View File

@ -0,0 +1,128 @@
// src/pages/DatabaseTestPage.js
import React, {useState, useEffect} from 'react';
import {
View,
Text,
TextInput,
Button,
ScrollView,
StyleSheet,
} from 'react-native';
import {initializeDatabase} from '../utils/DatabaseService';
const DatabaseTestPage = () => {
const [db, setDb] = useState(null);
const [users, setUsers] = useState([]);
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
useEffect(() => {
initializeDatabase().then(database => {
setDb(database);
fetchUsers(database);
});
}, []);
const fetchUsers = database => {
database.transaction(tx => {
tx.executeSql('SELECT * FROM Users', [], (tx, results) => { m
const fetchedUsers = [];
for (let i = 0; i < results.rows.length; i++) {
fetchedUsers.push(results.rows.item(i));
}
setUsers(fetchedUsers);
});
});
};
const addUser = () => {
if (db && username && email) {
db.transaction(tx => {
tx.executeSql(
'INSERT INTO Users (username, email, created_at, updated_at) VALUES (?, ?, datetime("now"), datetime("now"))',
[username, email],
() => {
fetchUsers(db);
setUsername('');
setEmail('');
},
);
});
}
};
const deleteUser = userId => {
if (db) {
db.transaction(tx => {
tx.executeSql('DELETE FROM Users WHERE id = ?', [userId], () => {
fetchUsers(db);
});
});
}
};
return (
<ScrollView style={styles.container}>
<View style={styles.form}>
<TextInput
style={styles.input}
placeholder="Username"
value={username}
onChangeText={setUsername}
/>
<TextInput
style={styles.input}
placeholder="Email"
value={email}
onChangeText={setEmail}
/>
<Button title="Add User" onPress={addUser} />
</View>
<View style={styles.usersList}>
{users.map(user => (
<View key={user.id} style={styles.userItem}>
<Text style={styles.userText}>
{user.id}: {user.username} - {user.email}
</Text>
<Button title="Delete" onPress={() => deleteUser(user.id)} />
</View>
))}
</View>
</ScrollView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
marginTop: 50,
},
form: {
marginBottom: 20,
},
input: {
marginBottom: 10,
borderWidth: 1,
borderColor: '#ccc',
paddingHorizontal: 10,
paddingVertical: 5,
},
usersList: {
borderTopWidth: 1,
borderColor: '#ccc',
},
userItem: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 10,
borderBottomWidth: 1,
borderColor: '#ccc',
},
userText: {
fontSize: 16,
},
});
export default DatabaseTestPage;

View File

@ -0,0 +1,66 @@
// DatabaseService.js
import SQLite from 'react-native-sqlite-storage';
SQLite.enablePromise(true);
const databaseName = 'MyAccountApp.db';
const databaseVersion = '1.0';
const databaseDisplayName = 'My Account App Database';
const databaseSize = 200000; // 大约 200KB
async function initializeDatabase() {
try {
const db = await SQLite.openDatabase(
databaseName,
databaseVersion,
databaseDisplayName,
databaseSize,
);
await db.transaction(async tx => {
// 创建 Users 表
await tx.executeSql(
'CREATE TABLE IF NOT EXISTS Users (id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR(30), password VARCHAR(30), email VARCHAR(30), created_at DATETIME, updated_at DATETIME)',
);
// 创建 Accounts 表
await tx.executeSql(
'CREATE TABLE IF NOT EXISTS Accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, name VARCHAR(30), currency VARCHAR(10), balance DECIMAL, created_at DATETIME, updated_at DATETIME)',
);
// 创建 Ledgers 表
await tx.executeSql(
'CREATE TABLE IF NOT EXISTS Ledgers (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, name VARCHAR(30), created_at DATETIME, updated_at DATETIME)',
);
// 创建 Transactions 表
await tx.executeSql(
'CREATE TABLE IF NOT EXISTS Transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, ledger_id INTEGER, account_id INTEGER, type VARCHAR(10), amount DECIMAL, currency VARCHAR(10), date DATE, description VARCHAR(255), created_at DATETIME, updated_at DATETIME)',
);
// 创建 FixedExpenses 表
await tx.executeSql(
'CREATE TABLE IF NOT EXISTS FixedExpenses (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, name VARCHAR(30), amount DECIMAL, frequency VARCHAR(10), created_at DATETIME, updated_at DATETIME)',
);
// 创建 Subscriptions 表
await tx.executeSql(
'CREATE TABLE IF NOT EXISTS Subscriptions (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, name VARCHAR(30), amount DECIMAL, start_date DATE, end_date DATE, created_at DATETIME, updated_at DATETIME)',
);
// 创建 AAPayments 表
await tx.executeSql(
'CREATE TABLE IF NOT EXISTS AAPayments (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, event VARCHAR(30), total_amount DECIMAL, participants INTEGER, paid_by INTEGER, created_at DATETIME, updated_at DATETIME)',
);
// 其他表的创建语句...
});
console.log('Database initialized');
return db;
} catch (error) {
console.error('Error initializing database:', error);
}
}
export {initializeDatabase};