Kivy and database

3,479 views
Skip to first unread message

SAVERIO FLORIO

unread,
Jul 10, 2015, 6:04:39 AM7/10/15
to kivy-...@googlegroups.com
Hi,
I am studyng Kivy and i want to ask you if it can connect to some database?

Thanks

John Fabiani

unread,
Jul 10, 2015, 10:39:38 AM7/10/15
to kivy-...@googlegroups.com
On the desktop not an issue - just use any of the DBAPI tools available and it will work.  On mobile I have discovered that Postgres works if you use p8000 (completely pure python DBAPI tool).  But others (MS SQL, MySQL) have not worked for me.  I end up creating a restful API to allow database CRUD from Kivy.  There is a MS SQL module claiming that it's pure python but requires ctypes and I couldn't get it to work on Android.  I also tried using java classes without success (almost got it to work).  Sorry I have not tried any other dababases.

ZenCODE

unread,
Jul 10, 2015, 11:31:13 AM7/10/15
to kivy-...@googlegroups.com
Just in case it's not obvious, sqlite? https://docs.python.org/2/library/sqlite3.html

Bill Eaton

unread,
Jul 12, 2015, 10:16:23 PM7/12/15
to kivy-...@googlegroups.com
Another vote for sqlite. Especially if you're targeting mobile platforms.

Anushree

unread,
Oct 25, 2017, 5:10:33 AM10/25/17
to Kivy users support
Hi 


I'm trying to build a calendar app with kivy , python and SQLite. The application worked as expected in desktop but in I'm facing error when i package the application for an android device.
The application launches displaying the text loading and then closes all of a sudden.
I could not pin point the issue hence build an app with just 2 buttons where on click of 1 button i am moving to another screen with the 2nd button. This worked perfectly in an android mobile device as well.
Hence I added a few db components and build the app again facing the same issue as the previous app.

Can you help me find where am i going wrong.

main.py

import sqlite3
import os.path
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition

class DBClass():
    
    def __init__(self):
        
        self.conn= sqlite3.connect('DUMMY_SCHEMA.db')
        print("\n DB schema created successfully")
        self.c=self.conn.cursor()
        self.createDBSchema(self)

        # created db already and trying to connect to the db file created.
        #self.db_path = "./DUMMY_SCHEMA.db"
        #self.conn= sqlite3.connect(self.db_path)
        #self.c=self.conn.cursor()
    
    def getDBpath(self):
        return self.db_path;
    
    def getCursor(self):
        return self.c;
    
    def getConnection(self):
        return self.conn; 

    def close(self):
        try:
            self.c.close()
            self.conn.close()
        except sqlite3.ProgrammingError as e:
            print e
    
    def createDBSchema(self): 
        self.c.execute('''CREATE TABLE DUMMY( 
                                        FNAME TEXT,
                                        LNAME TEXT)''')

        print("\n Created Tables successfully")
        self.conn.commit()
        print("\n DB commands Commited")

        print("Insert values to tables")
        self.c.execute('''INSERT INTO DUMMY VALUES("Ramesh","C")''')
        self.c.execute('''INSERT INTO DUMMY VALUES("Saya","S")''')
        self.c.execute('''INSERT INTO DUMMY VALUES("CHANDRAN","N")''')
        print("Values inserted")
        self.conn.commit()
            
class MainScreen(Screen):
    pass

class AnotherScreen(Screen):
    pass
        

class ScreenManagement(ScreenManager):
    pass

presentation = Builder.load_file("main.kv")

class MainApp(App):
    db = DBClass()
       
    def build(self):
        return presentation
    
    def printdb(self):
        self.db.getCursor().execute('SELECT * FROM DUMMY')
        all_rows=self.db.getCursor().fetchall()
        for row in all_rows:
            print(row)
        
        self.db.close()
        
MainApp().run()


main.kv

ScreenManagement:
    MainScreen:
    AnotherScreen:
<MainScreen>:
    name: 'main'

    Button:
        on_release: app.root.current = 'other'
        text: 'Another Screen'
        font_size: 50
            
<AnotherScreen>:
    name: 'other'

    Button:
        on_release: app.root.current = app.printdb()
        text: 'back to the home screen'
        font_size: 50


From the logs i could find that the db file is locked with code 5 error.
Have attached the logs and buildozer.spec file

Thanks in advance,
Anushree



 
buildozer.spec
logs.txt

Tyler

unread,
Oct 25, 2017, 7:56:43 AM10/25/17
to Kivy users support
Hi, it seems to me that you're looking at the wrong db error, in the log there are also these lines:

10-25 13:56:44.033 30751 30845 I python  : Traceback (most recent call last):

10-25 13:56:44.033 30751 30845 I python  :   File "/home/anushree_tp/App/eclipseO2_workspace/Trial/src/.buildozer/android/app/main.py", line 1, in <module>

10-25 13:56:44.033 30751 30845 I python  :   File "/home/anushree_tp/App/eclipseO2_workspace/Trial/src/.buildozer/android/platform/build/dists/screen/private/lib/python2.7/sqlite3/__init__.py", line 24, in <module>

10-25 13:56:44.033 30751 30845 I python  :   File "/home/anushree_tp/App/eclipseO2_workspace/Trial/src/.buildozer/android/platform/build/dists/screen/private/lib/python2.7/sqlite3/dbapi2.py", line 27, in <module>

10-25 13:56:44.034 30751 30845 I python  : ImportError: No module named _sqlite3

10-25 13:56:44.037 30751 30845 I python  : Python for android ended.

Where it says that for whatever reason it couldn't load sqlite3 module from your python2 build, a fast google search of those errors indicates that it's custom compile related, and reinstall/rebuild of python with the needed development libraries solves the issue.
My suggestion is to try looking along those lines , maybe omit the python2 from the recipe and see where it gets you.

Anushree

unread,
Oct 31, 2017, 5:49:51 AM10/31/17
to Kivy users support
Thanks for pointing me to the correct error. 
I installed libsqlite3-dev from the package manager, recompiled python, and now i am not facing import error but i am facing the same issue as before.

In the calendar app , I created a class to perform all the db operations. 
I have a class created for each component in the app . In respective  class where i need to perform db operations I am creating an instance of the DB class.

DBCLASS

import sqlite3
import os.path

class DBClass():
    path = os.path.dirname(os.path.abspath(__file__))+'/CALENDER_APP.db'
    
    def __init__(self):  
        
        print("\n\n\n %s \n\n\n" ,self.path)
        
        if not (os.path.isfile(self.path)):
            self.conn= sqlite3.connect('CALENDER_APP.db')
            print("\n DB schema created successfully")
            self.c=self.conn.cursor()
            self.createDBTables()
            self.createDBEntries()
            self.close()
        
                        
    def createDBConnection(self):
        self.conn= sqlite3.connect(self.path)
        self.c=self.conn.cursor()
        
    
    def getDBpath(self):
        return self.path;
    
    def getCursor(self):
        return self.c;
    
    def getConnection(self):
        return self.conn; 

    def close(self):
        try:
            self.c.close()
            self.conn.close()
        except sqlite3.ProgrammingError as e:
            print e
    
    def createDBTables(self): 
        try:
            self.c.execute('''CREATE TABLE USER_DETAILS( 
                                        USER_ID INT PRIMARY KEY NOT NULL UNIQUE,
                                        FNAME TEXT,
                                        LNAME TEXT,
                                        EMAIL BLOB UNIQUE)''')
            self.c.execute('''CREATE TABLE LOGIN_DETAILS(
                                        USER_ID INT PRIMARY KEY ,
                                        USERNAME TEXT NOT NULL UNIQUE,
                                        PASSWORD BLOB NOT NULL UNIQUE,
                                        FOREIGN KEY(USER_ID) REFERENCES USER_DETAILS(USER_ID) )''')
            self.c.execute('''CREATE TABLE USER_GROUPS(
                                        GRP_ID INT PRIMARY KEY NOT NULL UNIQUE,
                                        GRP_NAME TEXT UNIQUE)''')
            self.c.execute('''CREATE TABLE REASON_CODES(
                                        CODE_TYPE VARCHAR(15) UNIQUE NOT NULL,
                                        CODE_VALUE VARCHAR(20) UNIQUE NOT NULL)''')
            self.c.execute('''CREATE TABLE USR_BELONGS_GRP(
                                            GRP_ID INT,
                                            USER_ID INT,
                                            FOREIGN KEY(GRP_ID) REFERENCES USER_GROUPS(GRP_ID),
                                            FOREIGN KEY(USER_ID) REFERENCES USER_DETAILS(USER_ID))''')
            self.c.execute('''CREATE TABLE USR_TRANSCATIONS(
                                            USER_ID INT,
                                            START_DATE DATETIME DEFAULT CURRENT_TIMESTAMP,
                                            END_DATE DATETIME DEFAULT CURRENT_TIMESTAMP,
                                            REASON VARCHAR(20),
                                            FOREIGN KEY(REASON) REFERENCES REASON_CODES(CODE_VALUE),
                                            FOREIGN KEY(USER_ID) REFERENCES USER_DETAILS(USER_ID))''')
            self.conn.commit()
        except sqlite3.ProgrammingError as e:
            print (e)
        
        print("\n Created Tables successfully")
        
    
    def createDBEntries(self):
        print("Insert values to tables")
        try:
            self.c.execute('''INSERT INTO USER_DETAILS VALUES(1,"Anushree", "TP", "a...@in.ibm.com")''')
            self.c.execute('''INSERT INTO LOGIN_DETAILS VALUES(1,"anush", "password")''')
            self.c.execute('''INSERT INTO REASON_CODES VALUES("LEAVE", "Leave")''')
            self.c.execute('''INSERT INTO USR_TRANSCATIONS VALUES(1,'2017-07-09 10:00:00','2017-07-09 10:00:00',"Leave")''')
            self.c.execute('''INSERT INTO REASON_CODES VALUES("VACATION", "Vacation")''')
            self.conn.commit()
            
        except sqlite3.ProgrammingError as e:
            print (e)
        
        print("All Values inserted")
        print("Values inserted are:")
        
        try:
            print("USER DETAILS\n\n")
            for row in self.c.execute('SELECT * FROM USER_DETAILS'):
                print (row)
            
            print("LOGIN_DETAILS\n\n")    
            for row in self.c.execute('SELECT * FROM LOGIN_DETAILS'):
                print (row)
                
            print("REASON_CODES\n\n")    
            for row in self.c.execute('SELECT * FROM REASON_CODES'):
                print (row)
                
            print("USR_TRANSCATIONS\n\n")    
            for row in self.c.execute('SELECT * FROM USR_TRANSCATIONS'):
                print (row)
                
        except sqlite3.ProgrammingError as e:
            print (e)

 

In respective class for each component i am creating a connection performing the operations and closing the connection.


        self.db.createDBConnection() 
        self.db.getCursor().execute('SELECT * FROM USR_TRANSCATIONS')
        all_rows=self.db.getCursor().fetchone()
        for row in all_rows:
            print(row)
        #row1=list(all_rows)      
        self.db.close()

When I searched the error 

SQLiteLog: (5) database is locked

10-31 14:41:14.720  4336 25215 E SQLiteDatabase: Failed to open database '/data/user/0/com.android.vending/databases/verify_apps.db'.

10-31 14:41:14.720  4336 25215 E SQLiteDatabase: android.database.sqlite.SQLiteDatabaseLockedException: database is locked (code 5): , while compiling: PRAGMA journal_mode

I found that the error occurs when there are multiple connections open. Hence i closed the connection once the operation is performed.

Can someone point me to the right direction i.e  if i am looking at the wrong error again, or if my approach is wrong.

Thanks in advance.
CalendarApp.txt
Reply all
Reply to author
Forward
0 new messages