Tea Tree
Tea Tree

Reputation: 61

How to Insert json object into sqlite in react native?

How to store json object in react native sqlite storage?

How to insert JSON OBJECT data into SQLite

Hello, I'm using react-native-sqlite-storage library, and i need to insert a json object into a table, and i have no idea how to approach the matter given that i have checked previous posts, please help.

Upvotes: 0

Views: 1622

Answers (1)

Tea Tree
Tea Tree

Reputation: 61

This is the answer to my own question, it was just a matter of using right import which was a hell to find(import SQLite from 'react-native-sqlite-2') , but thankfully i found it with the help of the following links: Hopefully this would help someone else.

https://npmmirror.com/package/react-native-sqlite-2/v/1.0.0 https://github.com/appasaheb4/Tutorial_JsonData-into-insert-sqlitedb-ios-android-reactNative

enter code here

import React from 'react';

import SQLite from 'react-native-sqlite-2'

const Colors = [
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    },
    {
        color: "blue",
        value: "#00f"
    },
    {
        color: "cyan",
        value: "#0ff"
    },
    {
        color: "magenta",
        value: "#f0f"
    },
    {
        color: "yellow",
        value: "#ff0"
    },
    {
        color: "black",
        value: "#000"
    }
]


const App = () => {


const db = SQLite.openDatabase('test.db', '1.0', '', 1)
db.transaction(function(txn) {
  txn.executeSql('DROP TABLE IF EXISTS Users', [])
  txn.executeSql(
    'CREATE TABLE IF NOT EXISTS Users(color_id INTEGER PRIMARY KEY NOT NULL, colors VARCHAR(30), Value VARCHAR(25))',
    []
  )
  for (var i = 0; i < Colors.length; i++) {
    const array = Colors[i];

    txn.executeSql('INSERT INTO Users (Value, colors) VALUES (?,?)', 
  [array.value,array.color])
  txn.executeSql('SELECT * FROM `users`', [], function(tx, res) {
    for (let i = 0; i < res.rows.length; ++i) {
      console.log('item:', res.rows.item(i))
    }
  })
}
})
return(null)
}
export default App;

Upvotes: 2

Related Questions