React Native TypeORM查询返回空数组

5vf7fwbs  于 2023-02-16  发布在  React
关注(0)|答案(1)|浏览(256)

我正在尝试从现有数据库检索数据。我最近从Expo托管切换到裸工作流,尝试使用TypeORM测试react-native-sqlite-storage。但是,TypeORM原始查询不断返回空数组,我不知道为什么。
这是我的代码,它基于https://dev.to/jgabriel1/expo-sqlite-typeorm-4mn8示例

字典屏幕.js

function DictionaryScreen(props) {
    const { ejRepository } = useDatabaseConnection();

    const handleinputWord = async () => {
        console.log(props.inputWord);  //=>this console.logs the text from the input below 
        try {
            const results = await ejRepository.getWordandMean(props.inputWord);
            
            console.log(results); //=> Here I expect an array of the query result but it only returns []

        } catch (error) {
            console.log(error)
        }
    }

    return(
                <View style={styles.searchContainer}>
                    <MaterialCommunityIcons name="text-search" color="white" size={30}/>
                    <TextInput
                        style={styles.input}
                        onChangeText={props.updateTextInput}
                        onSubmitEditing={handleinputWord}
                        value={props.inputWord}
                        placeholder='Look up the word (Type exactly)'
                        keyboardType="default"
                    /> 
                <StatusBar style='light' />
                </View>
           )
}

const mapStateToProps = state => {
    return { 
        inputWord: state.inputWord
    }
};
    
const mapDispatchToProps = {updateTextInput};
    
    
export default connect(mapStateToProps, mapDispatchToProps) (DictionaryScreen);

存储库.ts

export class EJRepository {
    private ormRepository: Repository<EJModel>;

    constructor(connection: Connection) {
      this.ormRepository = connection.getRepository(EJModel);
    }

    public async getWordandMean(props: any): Promise<EJModel> {
      console.log(props);  //=> this returns the same text from DictionaryScreen

      const results = await this.ormRepository.query(
        `SELECT * FROM ejmodel WHERE word LIKE '%${props}%';`, [props]);
 
      return results;
    }
}

连接.tsx

interface DatabaseConnectionContextData {
    ejRepository: EJRepository;
}
  
const DatabaseConnectionContext = createContext<DatabaseConnectionContextData>(
    {} as DatabaseConnectionContextData,
  );
  
export const DatabaseConnectionProvider: React.FC = ({ children }) => {
   const [connection, setConnection] = useState<Connection | null>(null);
  
   const connect = useCallback(async () => {
       const createdConnection = await createConnection({
          type: 'react-native',
          name: "ejdict.v1.0",
          database: '***.db',
          entities: [EJModel],
           location: 'default',
          migrations: [ejdict1621603544180],
          migrationsRun: true,
          synchronize: false,
           logging: true,
          extra: {createFromLocation: '/Users/***/***/ios/***/www/***.db' }
       });
  
       setConnection(createdConnection);
     }, []);
  
    useEffect(() => {
      if (!connection) {
        connect();
      }
    }, [connect, connection]);
  
    if (!connection) {
      return <ActivityIndicator />;
    }
  
return (
   <DatabaseConnectionContext.Provider
      value={{
        ejRepository: new EJRepository(connection),
      }}
    >
      {children}
    </DatabaseConnectionContext.Provider>
  );
};

export function useDatabaseConnection() {
  const context = useContext(DatabaseConnectionContext);

  return context;
}

EJ模型.ts

import {Entity, PrimaryColumn, Column} from "typeorm";

@Entity({name: "ejmodel"})
export class EJModel {

    @PrimaryColumn({type: 'integer'})
    item_id: number;

    @Column({type: 'text'})
    word: string;

    @Column({type: 'text'})
    mean: string;

    @Column({type: 'integer'})
    level: number;
}

PS:在React Native项目中加载现有数据库是一种不寻常的尝试吗?工作示例几乎不存在。我曾经在Expo上实现过它,但我意识到我需要迁移功能,并试图在TypeORM上做同样的事情,浪费了大量时间...

8xiog9wr

8xiog9wr1#

我已经通过以下步骤找到了这个问题的解决方案
1.调整表的实体以
@Entity({ name: YOUR_TABLE_NAME, synchronize: false, })
1.将现有数据库放入目录
android/app/src/main/assets or android/app/src/main/assets/www
1.声明类型
export const AppDataSource = new DataSource({ type: "react-native", database:database.db, location: "default", synchronize: true, entities: [YOUR_ENTITY], logging: ["error", "query", "schema"], });
//注意,如果您不想同步所有表,可以将其设置为false,或者可以像第1步那样在每个实体中单独设置。
4)如果已在物理设备中安装应用程序,请卸载该应用程序(因为应用程序不会更新数据库文件),然后再次运行构建

<code>cd android &&./gradlew clean
cd .. && react-native run-android</code>

相关问题