为什么我无法在react-native-sqlite-storage数据库上执行SQL命令?

问题描述 投票:0回答:1

作为大学项目的一部分,我正在与一个团队合作开发一个使用react-native-sqlite-storage API的react-native数据库应用程序。

目前的目标是确保我可以在数据库上执行 SQL 命令。不幸的是,当我检查数据库中的表是否存在时,我收到一个关于由以下错误引起的未处理的承诺拒绝的错误:

TypeError:db.executeSql 不是一个函数(未定义)

我不知道这是为什么。根据本教程,我应该能够直接在从 openDatabase 函数获取的数据库对象上调用executeSql(sql) 函数,并从中获取值。

如何使用react-native-sqlite-storage包在SQLite中执行SQL?

到目前为止,这是我们的应用程序:

import React from 'react';
import {Text, View} from 'react-native';
import {connectToDatabase, doesTableExist} from './code/DBAPI.js'
import {setupDBReceipts} from './code/DBAPI-receipts.js'
import {setupDBAttachments} from './code/DBAPI-attachments.js'

const App = () => {
    const db = connectToDatabase();
        if(!doesTableExist(db, "Receipts")){
        setupDBReceipts(db);
        setupDBAttachments(db)
        return (
            <View>
                <Text> Welcome to the app. The database has been set up for the first time :) </Text>
            </View>
        );
    }else{
        return (
            <View>
                <Text> Welcome to the app. The database has already been set up :) </Text>
            </View>
        );
    }
    
};

export default App;

这是迄今为止我们数据库代码的一部分:

import React from 'react';
import {openDatabase, SQLiteDatabase} from "react-native-sqlite-storage";

/**
 * Connect to the App database
 * 
 * @returns a database object
 */
export const connectToDatabase = async() => {
    return openDatabase({name: 'app.db', location: 'default'});
}

/**
 * Sanitises a string. Keep in mind that URIs and URLs may be part of our input fields, so this may be tricky...
 * @param the string input to sanitise
 * @returns the string that is sanitised
 * @alpha Not finished yet, do not use this function!
 */
export const sanitiseString = (input) => {
    return input;
}

/**
 * Tests whether the database contains the given table
 */
export const doesTableExist = async(db, tableName) => {
    tableName = sanitiseString(tableName);
    value = await db.executeSql("SELECT EXISTS (SELECT " + tableName + " FROM sqlite_schema WHERE type='table');");
    return value == 1;
}

附注这是我第一次用 React-Native 编写,我几乎没有 JavaScript 经验,所以任何额外的指针都会受到赞赏!

javascript react-native sqlite react-native-cli
1个回答
0
投票

connectToDatabase
是一个
Async
函数,它返回
Promise
,你必须
await
then
它。

等待

const App = async () => {
    const db = await connectToDatabase();
    
    if(!doesTableExist(db, "Receipts")){
         // Rest of your code
    } else {
         // Else part
    } 
}

然后()

const App = () => {
    const db = connectToDatabase();
    
    db.then(connection => {
        if(!doesTableExist(connection, "Receipts")){
             // Rest of your code
        } else {
             // Else part
        }
    });      
}
© www.soinside.com 2019 - 2024. All rights reserved.