You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.3 KiB
82 lines
2.3 KiB
import { ThemedText } from '@/components/ThemedText';
|
|
import { View } from 'react-native';
|
|
import { Button, ButtonText } from '@/components/ui/button';
|
|
import SQLite from 'react-native-sqlite-storage';
|
|
import { useEffect, useRef } from 'react';
|
|
|
|
SQLite.enablePromise(true);
|
|
// 打开数据库
|
|
const openDB = () => {
|
|
return SQLite.openDatabase({
|
|
name: 'test.db',
|
|
location: 'default',
|
|
})
|
|
};
|
|
|
|
// 创建表
|
|
const createTable = (db: SQLite.SQLiteDatabase) => {
|
|
db.transaction(tx => {
|
|
db.executeSql(
|
|
'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)',
|
|
[]
|
|
)
|
|
.then(() => {
|
|
console.log('表创建成功');
|
|
})
|
|
.catch(err => {
|
|
console.error('表创建失败:', err);
|
|
});
|
|
});
|
|
};
|
|
|
|
// 插入数据
|
|
const insertData = (db: SQLite.SQLiteDatabase) => {
|
|
db.transaction(tx => {
|
|
db.executeSql('INSERT INTO users (name, age) VALUES (?,?)', ['John', 30])
|
|
.then(() => {
|
|
console.log('数据插入成功');
|
|
})
|
|
.catch(error => console.error('数据插入失败:', error));
|
|
});
|
|
};
|
|
|
|
// 查询数据
|
|
const queryData = (db: SQLite.SQLiteDatabase) => {
|
|
db.transaction(tx => {
|
|
tx.executeSql('SELECT * FROM users', []).then(([_,result]) => {
|
|
const rows = result.rows;
|
|
for (let i = 0; i < rows.length; i++) {
|
|
console.log('用户信息:', rows.item(i));
|
|
}
|
|
}).catch(error => console.error('数据查询失败:', error));
|
|
});
|
|
};
|
|
|
|
export default function Mine() {
|
|
const dbRef = useRef<SQLite.SQLiteDatabase>();
|
|
// useEffect(() => {
|
|
// dbRef.current = openDB()
|
|
// },[])
|
|
return (
|
|
<View className='gap-2 px-4'>
|
|
<ThemedText>Database TEST</ThemedText>
|
|
<Button onPress={() => {openDB().then((db)=> {
|
|
console.log('connect success')
|
|
dbRef.current = db
|
|
}).catch((error)=> {
|
|
console.log('connect fail', error)
|
|
})}}>
|
|
<ButtonText>CONNECT</ButtonText>
|
|
</Button>
|
|
<Button onPress={() => createTable(dbRef.current!)}>
|
|
<ButtonText>CREATE TABLE</ButtonText>
|
|
</Button>
|
|
<Button onPress={() => insertData(dbRef.current!)}>
|
|
<ButtonText>INSERT</ButtonText>
|
|
</Button>
|
|
<Button onPress={() => queryData(dbRef.current!)}>
|
|
<ButtonText>QUERY</ButtonText>
|
|
</Button>
|
|
</View>
|
|
);
|
|
}
|