I stucked with SQLite database in React Native and I don't know what is a problem actually.
I am opening database, create table and try to insert some random data but when I am trying to display inserted data there is empty array. I am not sure its an error with insert or displaying or maybe my whole database is opened wrong.
Here I am opening database:
import SQLite from 'react-native-sqlite-storage';
SQLite.DEBUG(false);
SQLite.enablePromise(false);
export const db = SQLite.openDatabase(
{
name: 'baza.db'
}
);
and here I am creating table and trying to insert data and display it:
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);
}
);
});
}
My logs after creating table and insert data:
[Info] 06-10 10:47:50.486 5866 5924 I ReactNativeJS: 'item:', 0
[Info] 06-10 10:47:55.412 5866 5924 I ReactNativeJS: []
Any idea what is wrong or maybe how I should do this? I will be very grateful
You can check column type, because change type int to varchar in SQLite, because react native is sending string type.