Giter Site home page Giter Site logo

react-native-sqlite's Introduction

react-native-sqlite

NOTE: This hasn't been maintained for a while and was never very complete to start with. Check out https://github.com/andpor/react-native-sqlite-storage for a more usable library!

A binding for sqlite3 for React Native. Allows a database to be opened and for SQL queries to be run on it.

Written by Thomas Parslow (almostobsolete.net and tomparslow.co.uk) as part of Active Inbox (activeinboxhq.com).

Installation

Install using npm with npm install --save react-native-sqlite

You then need to add the Objective C part to your XCode project. Drag AIBSQLite.xcodeproj from the node_modules/react-native-sqlite folder into your XCode project. Click on the project in XCode, goto Build Phases then Link Binary With Libraries and add libAIBSQLite.a and libsqlite3.dylib.

NOTE: Make sure you don't have the AIBSQLite project open seperately in XCode otherwise it won't work.

Usage

var sqlite = require('react-native-sqlite');
sqlite.open("filename.sqlite", function (error, database) {
  if (error) {
    console.log("Failed to open database:", error);
    return;
  }
  var sql = "SELECT a, b FROM table WHERE field=? AND otherfield=?";
  var params = ["somestring", 99];
  database.executeSQL(sql, params, rowCallback, completeCallback);
  function rowCallback(rowData) {
    console.log("Got row data:", rowData);
  }
  function completeCallback(error) {
    if (error) {
      console.log("Failed to execute query:", error);
      return
    }
    console.log("Query complete!");
    database.close(function (error) {
      if (error) {
        console.log("Failed to close database:", error);
        return
      }
    });
  }
});

Database Location

It will first look for the database filename you give in the Documents directory inside the app sandbox. If it doesn't find anything there it will look in the app bundle and try and copy it to the Documents directory. If it doesn't find the database in either place then it will create a new blank database in the Documents directory.

In the future it should probably be made possible to open/create databases in the tmp and Libraries directories.

Known Issues

  • Doesn't support reading of BLOB fields right now. I'm not entirely sure what would be the best way to pass back binary data. Maybe Base64?
  • Database needs to be closed manually. I'm not sure how I could do this automatically.

Feedback Welcome!

Feedback, questions, suggestions and most of all Pull Requests are very welcome. This is an early version and I want to figure out the best way to continue it.

I'm also available for freelance work!

I'm @almostobsolete on Twitter my email is [email protected] and you can find me on the web at tomparslow.co.uk and almostobsolete.net

react-native-sqlite's People

Contributors

almost avatar antoniopresto avatar barbarosh avatar dmfrancisco avatar jbogard avatar lookfirst avatar pcottle avatar propan avatar riyuk avatar sreejithr avatar srounce avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-sqlite's Issues

Cannot read property 'setState' of undefined

Hello!
when i read all datas from DB , after get all datas and then set this.state,but have a error like this:'Cannot read property 'setState' of undefined'.Please tell me why.
Thank you!

code:
componentDidMount:function(){

    SQLite.open("iphone.sqlite",function(error,database){

        if (error) {
            console.log("open database fail:",error);
            return;
        }
        console.log("open database successfully");



        database.executeSQL("select * from goods",[],(row) => {
            results.push(row);

        },(error) => {
            if (error) {

                console.log("error:",error);

            }else{

                console.log("results datas:",results);
                this.setState({
                    loaded:true,
                    dataSource:this.state.dataSource.cloneWithRows(results),
                });


            }
    });

});

},

Cannot install with React Native 0.7.x

When I try to npm install --save react-native-sqlite I get the following error:

npm ERR! peerinvalid The package react-native does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants react-native@^0.6.0

Cannot install with RN 0.0.60

FYI: :(

npm install --save react-native-sqlite

jgarcia-15in:KGMP jgarcia$ npm  install [email protected] -force
npm WARN using --force I sure hope you know what you are doing.
npm ERR! Darwin 14.3.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "[email protected]" "-force"
npm ERR! node v0.12.0
npm ERR! npm  v2.5.1
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package react-native does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants react-native@^0.5.0

npm ERR! Please include the following file with any support request:
npm ERR!     /www/ios/KeyGenMusicPlayer/KGMP/npm-debug.log
jgarcia-15in:KGMP jgarcia$ vi package.json 
jgarcia-15in:KGMP jgarcia$ npm install --save react-native-sqlite
npm ERR! Darwin 14.3.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "--save" "react-native-sqlite"
npm ERR! node v0.12.0
npm ERR! npm  v2.5.1
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package react-native does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants react-native@^0.5.0

npm ERR! Please include the following file with any support request:
npm ERR!     /www/ios/KeyGenMusicPlayer/KGMP/npm-debug.log

How to close database in React View?

Hi, i put the open database code in the didComponentMounted method, but how to get the database reference in the didComponentWillUnmount method to release the database connection?

Fails Even Without Db Connection

First off, excellent work and thank you for contributing to the React community. Now for my issue... I followed the directions of your readme and can successfully compile my app but it fails after 5 sec even though I have made no Db connection. Here is the stack:

2015-04-18 16:09:04.656 BDSios[14772:5069979] *** Assertion failure in -RCTModuleMethod initWithReactMethodName:objCMethodName:JSMethodName:, /Users/james/Projects/BDSios/node_modules/react-native/React/Base/RCTBridge.m:328
2015-04-18 16:09:04.661 BDSios[14772:5069979] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'You are attempting to export the method -[AIBSQLite **rct_export__prepareStatement:sql:andParams:callback:], but oseDatabase: does not conform to the RCTBridgeModule Protocol'
* First throw call stack:
(
0 CoreFoundation 0x000000010ca6ec65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010bee0bb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010ca6eaca +[NSException raise:format:arguments:] + 106
3 Foundation 0x000000010baf5a57 -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 169
4 BDSios 0x000000010b7630f5 -[RCTModuleMethod initWithReactMethodName:objCMethodName:JSMethodName:] + 2565
5 BDSios 0x000000010b773d86 __RCTExportedMethodsByModuleID_block_invoke + 1046
6 libdispatch.dylib 0x000000010f8b7614 _dispatch_client_callout + 8
7 libdispatch.dylib 0x000000010f8a3881 dispatch_once_f + 565
8 BDSios 0x000000010b771ee1 RCTExportedMethodsByModuleID + 81
9 BDSios 0x000000010b774f42 __RCTRemoteModulesConfig_block_invoke_2 + 50
10 CoreFoundation 0x000000010c9a4f22 __53-[__NSArrayM enumerateObjectsWithOptions:usingBlock:]_block_invoke + 114
11 CoreFoundation 0x000000010c9a467c -[__NSArrayM enumerateObjectsWithOptions:usingBlock:] + 300
12 BDSios 0x000000010b774ef5 __RCTRemoteModulesConfig_block_invoke + 133
13 libdispatch.dylib 0x000000010f8b7614 _dispatch_client_callout + 8
14 libdispatch.dylib 0x000000010f8a3881 dispatch_once_f + 565
15 BDSios 0x000000010b76bdd0 RCTRemoteModulesConfig + 112
16 BDSios 0x000000010b76b317 -[RCTBridge setUp] + 2295
17 BDSios 0x000000010b76a9a2 -[RCTBridge initWithBundleURL:moduleProvider:launchOptions:] + 322
18 BDSios 0x000000010b7254d8 -[RCTRootView initWithBundleURL:moduleName:launchOptions:] + 152
19 BDSios 0x000000010b70b66d -[AppDelegate application:didFinishLaunchingWithOptions:] + 189
20 UIKit 0x000000010e4ca788 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 240
21 UIKit 0x000000010e4cb397 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 2540
22 UIKit 0x000000010e4ce1de -[UIApplication _runWithMainScene:transitionContext:completion:] + 1349
23 UIKit 0x000000010e4cd0d5 -[UIApplication workspaceDidEndTransaction:] + 179
24 FrontBoardServices 0x000000011190a5e5 __31-[FBSSerialQueue performAsync:]_block_invoke_2 + 21
25 CoreFoundation 0x000000010c9a241c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK
+ 12
26 CoreFoundation 0x000000010c998165 __CFRunLoopDoBlocks + 341
27 CoreFoundation 0x000000010c997923 __CFRunLoopRun + 851
28 CoreFoundation 0x000000010c997366 CFRunLoopRunSpecific + 470
29 UIKit 0x000000010e4ccb42 -[UIApplication _run] + 413
30 UIKit 0x000000010e4cf900 UIApplicationMain + 1282
31 BDSios 0x000000010b70b9cf main + 111
32 libdyld.dylib 0x000000010f8eb145 start + 1
33 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

What advise can you provide?

Thanks,

Chris

Option to execute queries synchronously

I have a function to execute queries:

var queryDB = function(sql, params, onComplete) {
  sqlite.open("filename.sqlite", function (error, database) {
    var data = []
    if (error) {
      console.log("Failed to open database:", error);
      return;
    }
    database.executeSQL(sql, params, rowCallback, completeCallback);
    function rowCallback(rowData) {
      data.push(rowData)
    }
    function completeCallback(error) {
      if (error) {
        console.log("Failed to execute query:", error);
        return
      }
      console.log("Query complete!");
      database.close(function (error) {
        if (error) {
          console.log("Failed to close database:", error);
          return
        }
      });
    }
  });
}

I'm trying to preload data from the database before starting my app:

var timers = [] // global

queryDB('SELECT * FROM Timers', [], function(data) {
 timers = data
})

Obviously, the code above doesn't work β€”Β it needs to be executed synchronously. And if I put AppRegistry.registerComponent inside the onComplete callback, it says that the application is not registered. Is there any way I can run the query synchronously?

Extra file "/w"

FYI,

Installed and found a file in the directory named: "/w"

image

Thanks for this addition to the React Native community!

joins using sqlite in react native?

does react native sqlite suport joins between tables,or is any package available that has support for joins.can you please provide me help or suggest some solution to manage relation between tables and getting data from them

No DB is generated in Document

I was able to complete everything up to the part where we query the DB. I get nothing and failed to execute query returns. I checked the sandbox and find no DB is generated.

dependency issue

Hi, I am a bit new in objective C, I tried your instructions adding sqlite to the project, but I got this error, any clues on how to fix it? Looks like it cannot find the react library.

Undefined symbols for architecture x86_64:
"__RCTLogFormat", referenced from:
-[AIBSQLite openFromFilename:callback:] in libAIBSQLite.a(AIBSQLite.o)
-[AIBSQLite closeDatabase:callback:] in libAIBSQLite.a(AIBSQLite.o)
-[AIBSQLite prepareStatement:sql:andParams:callback:] in libAIBSQLite.a(AIBSQLite.o)
-[AIBSQLite stepStatement:statementId:callback:] in libAIBSQLite.a(AIBSQLite.o)
-[AIBSQLite finalizeStatement:statementId:callback:] in libAIBSQLite.a(AIBSQLite.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Alternatives to using RCTDeviceEventEmitter for data streaming

I'm using events on RCTDeviceEventEmitter to pass back rows from queries, is this the best way to do it?

One of the options would be to build a concept of a cursor. This way client JS code will have full control over data streaming:

  • spread data fetching across multiple runloop iterations
  • cancel fetching data before reaching end

API could look something like that:

database.executeSQL(sql, params, (error, cursor) => {
  console.log(cursor.count());
  cursor.on('end', () => console.log('The End.'));
  cursor.next((record) => { console.log(record); });
  cursor.next(20, (records) => { 
    console.log('Got 20 more: ', records);
    cursor.stop();
  });
});

Note that using this you can still support your current API

Question : What is the best way to act on "No rows returned"?

Hi. Thank you for the plugin, looks great. I've been trying it out but have noticed I'm getting some race/scope conditions because of how I'm trying to handle the event "0 rows returned".

What is the intended way to handle this?

Use case:

I receive a packet of data. I want to see if a record with a matching ID already exists. If so, update it, if not insert new.

My understanding is that the completionHandler triggers all the time and row triggers only when rows are received. This means there is no way to check for no rows without setting an adhoc var before the query

var hasRows = false;

then in rowHandler()

hasRows = true;

then in completionHandler()

if (!hasRows){
// 0 rows returned
}

Am I missing something?

My Db is locked and I want to delete it

My Db is locked and I want to delete it, where can I find it? I read that it's in Documents directory inside the app sandbox but that's not specific enough for me.

Unable to generate AppStore archive with this library

We are unable to generate App Store archive when using this library in linked libraries. It works OK when running for simulator or Adhoc binary for device. But it does not create valid XCode archive for Appstore when creating Archive for AppStore in XCode.

http://take.ms/87m8k

Any one successfully deploy app to AppStore using this? Any other steps we need to do to make it work for AppStore?

Can't open database

So I created an .sql and .sqlite file through the Terminal.

I created the same table and inserted one row. To see if I could read from it.

I placed the files in the same place as in the react-native-sqlite-example and both of them don't work.

The error message while selecting all rows (select * from table;) basically returns the error message:

No such table: teste (teste is my table btw)

So I see someone here got a similar error. No file is created either. I would love to have this working.

Tried 3 different ways. Can't get this to work

First, I did:

  1. npm install --save react-native-sqlite while inside my app's directory. It installed inside the node_modules/ inside app directory.
  2. Dragged AIBSQLite.xcodeproj into my project.
  3. Added libAIBSQLite.a into my build phases. But the library was shown in red and xcode build failed without any error messages.

Second,

  1. I went to my home (~) and did sudo npm install react-native-sqlite and it installed in ~/node_modules/.
  2. Added AIBSQLite.xcodeproj to project. libAIBSQLite.a was still red, but it built successfully.
  3. But when I added this line var sqlite = require('./react-native-sqlite') in a file, I got Requiring unknown module error in the simulator.
    I tried restarting the packager. No use. I even tried require('react-native-sqlite'). No use.
    ios simulator screen shot 07-apr-2015 5 14 43 pm

Lastly,

  1. Added react-native-sqlite: '*' to my app's package.json. Did npm install.
  2. Had the same issue from the 1st method. ie, xcode failed without any error messages.

How do I make this work?

Can't drag libsqlite3.dylib to the 'Link Binary With Libraries'

Hi,
I installed the the npm package. Then dragged the AIBSQLite.xcodeproj to the my project. Dragged the libAIBSQLite.a file to the 'Link Binary With Libraries'. But, when I try to drag the libsqlite3.dynlib to the 'Link Binary With Libraries' it just returns back (It just doesn't let me add it to the list).

What am I doing wrong?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.