0

我在 React Native 中坚持使用 SQLite 数据库,但我不知道实际上是什么问题。

我正在打开数据库,创建表并尝试插入一些随机数据,但是当我尝试显示插入的数据时,有一个空数组。我不确定插入或显示是否出错,或者我的整个数据库打开错误。

我在这里打开数据库:

import SQLite from 'react-native-sqlite-storage';
SQLite.DEBUG(false);
SQLite.enablePromise(false);

export const db = SQLite.openDatabase(
    {
        name: 'baza.db'
    }
);

在这里我正在创建表并尝试插入数据并显示它:

fun = () => {
      db.transaction(function (txn) {
        txn.executeSql(
          "SELECT name FROM sqlite_master WHERE type='table' AND name='Test_Table'",
          [],
          function (tx, res) {
            console.log('item:', res.rows.length);
            if (res.rows.length == 0) {
              txn.executeSql('DROP TABLE IF EXISTS Test_Table', []);
              txn.executeSql(
                'CREATE TABLE IF NOT EXISTS Test_Table(test_id INTEGER PRIMARY KEY AUTOINCREMENT, test_value FLOAT, test_date VARCHAR(15))',
                []
              );
            }
          }
        );
      })
    }

    
    insertData = () => {
      db.transaction(function (tx) {
        tx.executeSql(
          'INSERT INTO Test_Table (test_value, test_date) VALUES (2, test)',
          (tx, results) => {
            console.log('Results', results.rowsAffected);
            if (results.rowsAffected > 0) {
              console.log('Data Inserted Successfully....');
            } else console.log('Failed....');
          }
        );
      });
      this.viewTable();
    }

    viewTable = () => {
      db.transaction((tx) => {
        tx.executeSql(
          'SELECT * FROM Test_Table',
          [],
          (tx, results) => {
            let temp = [];
            for (let i = 0; i < results.rows.length; ++i)
              temp.push(results.rows.item(i));
            console.log(temp);
          }
        );
      });
    }

创建表并插入数据后我的日志:

[Info] 06-10 10:47:50.486  5866  5924 I ReactNativeJS: 'item:', 0


[Info] 06-10 10:47:55.412  5866  5924 I ReactNativeJS: []

知道出了什么问题,或者我应该怎么做?我将不胜感激

4

3 回答 3

0

我以前也遇到过这个问题,但最后我可以让它工作。这是我所做的:

  1. 我在这里下载了数据库浏览器来创建和管理我的 sqlite 数据库。
  2. 如果此路径上不存在,则创建一个新文件夹root\android\app\src\main\assets\www并将创建的数据库放在www文件夹中。
  3. 在项目中,我为 sqlite 目的创建了一个单独的类/文件。

样品名称sqlite-db.js

import { openDatabase, deleteDatabase } from 'react-native-sqlite-storage';
var db = openDatabase(
    { name: 'sqlite.db', createFromLocation: 1 },
    () => {
        console.log('Connection success!');
    },
    error => {
        console.log(error);
    },
);
/// Below function is use in-case the db object is null
async function OpenDatabase() {
    db = openDatabase(
        { name: 'sqlite.db', createFromLocation: 1 },
        () => {
            console.log('Re-open connection success!');
        },
        error => {
            console.log(error);
        },
    );
}
function SQLSelect(query, params = []) {
    return new Promise(async (resolve, reject) => {
        if (db === null) {
            await OpenDatabase();
        }
        db.transaction(function (txn) {
            console.log('SQLITE SELECT QUERY:', query, ',Value:', params);
            txn.executeSql(query, params,
                function (tx, res) {
                    var temp = [];
                    if (res.rows.length == 0) {
                        resolve(temp);
                    }
                    for (let i = 0; i < res.rows.length; ++i) temp.push(res.rows.item(i));
                    console.log('SQLITE SELECT RESULT:', temp)
                    resolve(temp);
                },
                function (error) {
                    console.log('Failed to select:', error);
                    reject();
                },
            );
        });
    });
}
function SQLInsert(query, params = []) {
    return new Promise(async (resolve, reject) => {
        if (db === null) {
            await OpenDatabase();
        }
        db.transaction(function (txn) {
            console.log('SQLITE INSERT QUERY:', query, ',Value:', params);
            txn.executeSql(query, params,
                function (tx, res) {
                    console.log('SQLITE INSERT RESULT:', res)
                    resolve(res);
                },
                function (error) {
                    console.log('Failed to insert:', error);
                    reject();
                },
            );
        });
    });
}
function SQLUpdate(query, params = []) {
    return new Promise(async (resolve, reject) => {
        if (db === null) {
            await OpenDatabase();
        }
        await db.transaction(function (txn) {
            console.log('SQLITE UPDATE QUERY:', query, ',Value:', params);
            txn.executeSql(query, params,
                function (tx, res) {
                    console.log('SQLITE UPDATE RESULT:', res);
                    if (res.rowsAffected > 0) {
                        // Data updated
                        resolve(res.rowsAffected);
                    } else {
                        // Data not updated
                        resolve(0);
                    }
                },
                function (error) {
                    console.log('Failed to update:', error);
                    reject();
                },
            );
        });
    });
}
function SQLDelete(query, params = []) {
    return new Promise(async (resolve, reject) => {
        if (db === null) {
            await OpenDatabase();
        }
        await db.transaction(function (txn) {
            console.log('SQLITE DELETE QUERY:', query, ',Value:', params);
            txn.executeSql(query, params,
                function (tx, res) {
                    console.log('SQLITE DELETE RESULT:', res)
                    if (res.rowsAffected > 0) {
                        // Data deleted
                        resolve(res.rowsAffected);
                    } else {
                        // Data not delete
                        reject();
                    }
                },
                function (error) {
                    console.log('Failed to delete:', error);
                    reject();
                },
            );
        });
    });
}

async function GetMeSomethingOnDB(data) {
    return new Promise(async (resolve, reject) => {
        try {
            var SQData = {
                "TABLERESULT": []
            }
            let params = [];
            let queries = '';
            params = [data.TableID];
            queries = `SELECT * FROM [TABLE] WHERE TableID=?`;
            await SQLSelect(queries, params).then(results => SQData.TABLERESULT = results).catch((error) => console.log('Error retrieve TABLERESULT. ', error));
            resolve(SQData);
        } catch (error) {
            console.log('ERROR GET SOMETHING:', error);
            reject();
        }
    });
}

你怎么能调用函数sqlite-db.js?示例如下: import * as ApxSQLite from "../../../sqlite-db";

React.useEffect(() => {
    //Get data directly to function
    let params = [];
    let queries = '';
    // You can add the parameter in the query or use ? and 
    // add the parameter ordinance in params array.
    queries = 'SELECT * FROM [OTHERTABLE] WHERE OtherID=1';
    ApxSQLite.SQLSelect(queries, params)
        .then((data) => {
            console.log('Mounted:', data);
        })
        .catch((error) => console.log('OTHERTABLE ERROR:', error));

    // Call the function in sqlite-db
    var data = {TableID : 13}
    ApxSQLite.GetMeSomethingOnDB(data)
        .then((data) => {
            console.log('Mounted 2:', data);
        })
        .catch((error) => console.log('GETSOMETHING ERROR:', error));
}, []);

顺便说一句,删除SQLite.DEBUG(false);SQLite.enablePromise(false);确实有帮助

于 2021-12-24T03:04:19.753 回答
0

我以前也遇到过这个问题,但最后我可以让它工作。以下是我为其他需要完整方法的人做的参考:

  1. 我在这里下载了数据库浏览器来创建和管理我的 sqlite 数据库设计。
  2. 如果此路径上不存在,则创建一个新文件夹root\android\app\src\main\assets\www并将创建的数据库放在www文件夹中。
  3. 在项目中,我为 sqlite 目的创建了一个单独的类/文件。

样品名称sqlite-db.js

import { openDatabase, deleteDatabase } from 'react-native-sqlite-storage';
var db = openDatabase(
    { name: 'sqlite.db', createFromLocation: 1 },
    () => {
        console.log('Connection success!');
    },
    error => {
        console.log(error);
    },
);
/// Below function is use in-case the db object is null
async function OpenDatabase() {
    db = openDatabase(
        { name: 'sqlite.db', createFromLocation: 1 },
        () => {
            console.log('Re-open connection success!');
        },
        error => {
            console.log(error);
        },
    );
}
function SQLSelect(query, params = []) {
    return new Promise(async (resolve, reject) => {
        if (db === null) {
            await OpenDatabase();
        }
        db.transaction(function (txn) {
            console.log('SQLITE SELECT QUERY:', query, ',Value:', params);
            txn.executeSql(query, params,
                function (tx, res) {
                    var temp = [];
                    if (res.rows.length == 0) {
                        resolve(temp);
                    }
                    for (let i = 0; i < res.rows.length; ++i) temp.push(res.rows.item(i));
                    console.log('SQLITE SELECT RESULT:', temp)
                    resolve(temp);
                },
                function (error) {
                    console.log('Failed to select:', error);
                    reject();
                },
            );
        });
    });
}
function SQLInsert(query, params = []) {
    return new Promise(async (resolve, reject) => {
        if (db === null) {
            await OpenDatabase();
        }
        db.transaction(function (txn) {
            console.log('SQLITE INSERT QUERY:', query, ',Value:', params);
            txn.executeSql(query, params,
                function (tx, res) {
                    console.log('SQLITE INSERT RESULT:', res)
                    resolve(res);
                },
                function (error) {
                    console.log('Failed to insert:', error);
                    reject();
                },
            );
        });
    });
}
function SQLUpdate(query, params = []) {
    return new Promise(async (resolve, reject) => {
        if (db === null) {
            await OpenDatabase();
        }
        await db.transaction(function (txn) {
            console.log('SQLITE UPDATE QUERY:', query, ',Value:', params);
            txn.executeSql(query, params,
                function (tx, res) {
                    console.log('SQLITE UPDATE RESULT:', res);
                    if (res.rowsAffected > 0) {
                        // Data updated
                        resolve(res.rowsAffected);
                    } else {
                        // Data not updated
                        resolve(0);
                    }
                },
                function (error) {
                    console.log('Failed to update:', error);
                    reject();
                },
            );
        });
    });
}
function SQLDelete(query, params = []) {
    return new Promise(async (resolve, reject) => {
        if (db === null) {
            await OpenDatabase();
        }
        await db.transaction(function (txn) {
            console.log('SQLITE DELETE QUERY:', query, ',Value:', params);
            txn.executeSql(query, params,
                function (tx, res) {
                    console.log('SQLITE DELETE RESULT:', res)
                    if (res.rowsAffected > 0) {
                        // Data deleted
                        resolve(res.rowsAffected);
                    } else {
                        // Data not delete
                        reject();
                    }
                },
                function (error) {
                    console.log('Failed to delete:', error);
                    reject();
                },
            );
        });
    });
}

async function GetMeSomethingOnDB(data) {
    return new Promise(async (resolve, reject) => {
        try {
            var SQData = {
                "TABLERESULT": []
            }
            let params = [];
            let queries = '';
            params = [data.TableID];
            queries = `SELECT * FROM [TABLE] WHERE TableID=?`;
            await SQLSelect(queries, params).then(results => SQData.TABLERESULT = results).catch((error) => console.log('Error retrieve TABLERESULT. ', error));
            resolve(SQData);
        } catch (error) {
            console.log('ERROR GET SOMETHING:', error);
            reject();
        }
    });
}

你怎么能调用函数sqlite-db.js?示例如下: import * as ApxSQLite from "./sqlite-db";

React.useEffect(() => {
    //Get data directly to function
    let params = [];
    let queries = '';
    // You can add the parameter in the query or use ? and 
    // add the parameter ordinance in params array.
    queries = 'SELECT * FROM [OTHERTABLE] WHERE OtherID=1';
    ApxSQLite.SQLSelect(queries, params)
        .then((data) => {
            console.log('Mounted:', data);
        })
        .catch((error) => console.log('OTHERTABLE ERROR:', error));

    // Call the function in sqlite-db if you do not want to
    // flood your screen script with all the things like ApxSQLite.SQLSelect code.
    var data = {TableID : 13}
    ApxSQLite.GetMeSomethingOnDB(data)
        .then((data) => {
            console.log('Mounted 2:', data);
        })
        .catch((error) => console.log('GETSOMETHING ERROR:', error));
}, []);

顺便说一句,我没有添加SQLite.DEBUG(false);SQLite.enablePromise(false);

于 2021-12-24T03:06:53.853 回答
-1

您可以检查列类型,因为在 SQLite 中将类型 int 更改为 varchar,因为 react native 正在发送字符串类型。

于 2021-08-22T00:03:14.373 回答