Qpython3, sqlite3 can't connect to database

2019-07-31 07:42发布

问题:

I'm beginner and I just try qpython for android.

I try to connect database at qpython3 by using sqlite3: My code

import sqlite3
conn=sqlite3.connect('mydatabase.db')

But it raises error and unable to open database file.

Any solution for this?? If I try at pc, it automatically create a database if not exists

回答1:

The reason it doesn't work is that QPython programs are run from '/' directory which of course is not writable to non-root users. You can check this with the following code run from the console.

import os
print(os.getcwd())

If you go to the ftp utility in the About menu, you will find a directory path that is being used by QPython3. On my HTC mobile it is:

/storage/emulated/0/com.hipipal.qpyplus

So I changed your example code to:

import os
import sqlite3
RootPath='/storage/emulated/0/com.hipipal.qpyplus'
conn=sqlite3.connect(os.path.join(RootPath,'mydatabase.db'))

and it works fine for me.

I also found that it is necessary to commit changes or they won't be written to the file. That is, end programs with:

conn.commit()
conn.close()