廓形仪rn版本-技术调研
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

3 months ago
3 months ago
3 months ago
3 months ago
  1. import { ThemedText } from '@/components/ThemedText';
  2. import { View } from 'react-native';
  3. import { Button, ButtonText } from '@/components/ui/button';
  4. import SQLite from 'react-native-sqlite-storage';
  5. import { useEffect, useRef } from 'react';
  6. SQLite.enablePromise(true);
  7. // 打开数据库
  8. const openDB = () => {
  9. return SQLite.openDatabase({
  10. name: 'test.db',
  11. location: 'default',
  12. })
  13. };
  14. // 创建表
  15. const createTable = (db: SQLite.SQLiteDatabase) => {
  16. db.transaction(tx => {
  17. db.executeSql(
  18. 'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)',
  19. []
  20. )
  21. .then(() => {
  22. console.log('表创建成功');
  23. })
  24. .catch(err => {
  25. console.error('表创建失败:', err);
  26. });
  27. });
  28. };
  29. // 插入数据
  30. const insertData = (db: SQLite.SQLiteDatabase) => {
  31. db.transaction(tx => {
  32. db.executeSql('INSERT INTO users (name, age) VALUES (?,?)', ['John', 30])
  33. .then(() => {
  34. console.log('数据插入成功');
  35. })
  36. .catch(error => console.error('数据插入失败:', error));
  37. });
  38. };
  39. // 查询数据
  40. const queryData = (db: SQLite.SQLiteDatabase) => {
  41. db.transaction(tx => {
  42. tx.executeSql('SELECT * FROM users', []).then(([_,result]) => {
  43. const rows = result.rows;
  44. for (let i = 0; i < rows.length; i++) {
  45. console.log('用户信息:', rows.item(i));
  46. }
  47. }).catch(error => console.error('数据查询失败:', error));
  48. });
  49. };
  50. export default function Mine() {
  51. const dbRef = useRef<SQLite.SQLiteDatabase>();
  52. // useEffect(() => {
  53. // dbRef.current = openDB()
  54. // },[])
  55. return (
  56. <View className='gap-2 px-4'>
  57. <ThemedText>Database TEST</ThemedText>
  58. <Button onPress={() => {openDB().then((db)=> {
  59. console.log('connect success')
  60. dbRef.current = db
  61. }).catch((error)=> {
  62. console.log('connect fail', error)
  63. })}}>
  64. <ButtonText>CONNECT</ButtonText>
  65. </Button>
  66. <Button onPress={() => createTable(dbRef.current!)}>
  67. <ButtonText>CREATE TABLE</ButtonText>
  68. </Button>
  69. <Button onPress={() => insertData(dbRef.current!)}>
  70. <ButtonText>INSERT</ButtonText>
  71. </Button>
  72. <Button onPress={() => queryData(dbRef.current!)}>
  73. <ButtonText>QUERY</ButtonText>
  74. </Button>
  75. </View>
  76. );
  77. }