使用现有数据库在Android应用中显示数据

时间:2019-02-04 10:06:47

标签: java android android-sqlite android-database

嗨,我是android开发的新手。 我已经创建了SQLite数据库并将其保存在Android Studio的资产文件夹中。我的应用程序必须使用现有数据库,而不是创建一个新数据库。我面临的问题是,当我想在屏幕上显示数据时,正在执行SQL语句的Cursor抛出错误。请帮助。

数据库名称为try { const client = new SimpleGraphClient(tokenResponse.token); const me = await client.getMe(); sql.connect(config, async function (err) { if (err) console.log(err); var request = new sql.Request(); request.query(`SELECT * FROM tradebot.accounts WHERE username='${username}' AND password='${password}'`, async function (err, recordset) { if (err) console.log(err); console.log(recordset); if (recordset.recordset.length == 1) { await turnContext.sendActivity({ text: 'Work', attachments: [CardFactory.adaptiveCard(mainmenu)] }); } else { await turnContext.sendActivity({ text: 'Dont work', attachments: [CardFactory.adaptiveCard(internal_login)] }); } sql.close(); }); }); } catch (error) { throw error; } ,表名称为test.db。 这是我的DataBaseHelper类

MASTER

这是我的TestAdapter类

public class DataBaseHelper extends SQLiteOpenHelper {
    private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
    //destination path (location) of our database on device
    private static String DB_PATH = "";
    private static String DB_NAME ="test,db";// Database name
    private SQLiteDatabase mDataBase;
    private final Context mContext;

    public DataBaseHelper(Context context)
    {
        super(context, DB_NAME, null, 1);// 1? Its database Version
        if(android.os.Build.VERSION.SDK_INT >= 17){
            DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
        }
        else
        {
            DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
        }
        this.mContext = context;
    }

    public void createDataBase() throws IOException
    {
        //If the database does not exist, copy it from the assets.

        boolean mDataBaseExist = checkDataBase();
        if(!mDataBaseExist)
        {
            this.getReadableDatabase();
            this.close();
            try
            {
                //Copy the database from assests
                copyDataBase();
                Log.e(TAG, "createDatabase database created");
            }
            catch (IOException mIOException)
            {
                throw new Error("ErrorCopyingDataBase");
            }
        }
    }

    //Check that the database exists here: /data/data/your package/databases/Da Name
    private boolean checkDataBase()
    {
        File dbFile = new File(DB_PATH + DB_NAME);
        //Log.v("dbFile", dbFile + "   "+ dbFile.exists());
        return dbFile.exists();
    }

    //Copy the database from assets
    private void copyDataBase() throws IOException
    {
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream mOutput = new FileOutputStream(outFileName);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer))>0)
        {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    //Open the database, so we can query it
    public boolean openDataBase() throws SQLException
    {
        String mPath = DB_PATH + DB_NAME;
        //Log.v("mPath", mPath);
        mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
        //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        return mDataBase != null;
    }

    @Override
    public synchronized void close()
    {
        if(mDataBase != null)
            mDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

这是我的MainActivity类

public class TestAdapter
    {
        protected static final String TAG = "DataAdapter";

        private final Context mContext;
        private SQLiteDatabase mDb;
        private DataBaseHelper mDbHelper;

        public TestAdapter(Context context)
        {
            this.mContext = context;
            mDbHelper = new DataBaseHelper(mContext);
        }

        public TestAdapter createDatabase() throws SQLException
        {
            try
            {
                mDbHelper.createDataBase();
            }
            catch (IOException mIOException)
            {
                Log.e(TAG, mIOException.toString() + "  UnableToCreateDatabase");
                throw new Error("UnableToCreateDatabase");
            }
            return this;
        }

        public TestAdapter open() throws SQLException
        {
            try
            {
                mDbHelper.openDataBase();
                mDbHelper.close();
                mDb = mDbHelper.getReadableDatabase();
            }
            catch (SQLException mSQLException)
            {
                Log.e(TAG, "open >>"+ mSQLException.toString());
                throw mSQLException;
            }
            return this;
        }

        public void close()
        {
            mDbHelper.close();
        }

        public Cursor getTestData() {
            try
            {
                String sql ="SELECT * FROM MASTER;";

                Cursor mCur = mDb.rawQuery(sql, null);
                if (mCur!=null)
                {
                    mCur.moveToNext();
                }
                return mCur;
            }
            catch (SQLException mSQLException)
            {
                Log.e(TAG, "getTestData >>"+ mSQLException.toString());
                throw mSQLException;
            }
        }
    }

这是logcat

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button=findViewById(R.id.submit);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TestAdapter mDbHelper = new TestAdapter(MainActivity.this);
                mDbHelper.createDatabase();
                mDbHelper.open();
                Cursor testdata = mDbHelper.getTestData();
                Toast.makeText(MainActivity.this,testdata.getString(0),Toast.LENGTH_SHORT).show();
                mDbHelper.close();
            }
        });

    }
}

日志猫说没有2019-02-04 15:47:30.227 2594-2594/com.example.myapplication E/SQLiteLog: (1) no such table: MASTER 2019-02-04 15:47:30.228 2594-2594/com.example.myapplication E/DataAdapter: getTestData >>android.database.sqlite.SQLiteException: no such table: MASTER (code 1): , while compiling: SELECT * FROM MASTER; 2019-02-04 15:47:30.228 2594-2594/com.example.myapplication D/AndroidRuntime: Shutting down VM 2019-02-04 15:47:30.242 2594-2594/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.myapplication, PID: 2594 android.database.sqlite.SQLiteException: no such table: MASTER (code 1): , while compiling: SELECT * FROM MASTER; at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58) at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37) at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46) at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1392) at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1331) at com.example.myapplication.TestAdapter.getTestData(TestAdapter.java:63) at com.example.myapplication.MainActivity$1.onClick(MainActivity.java:38) at android.view.View.performClick(View.java:6297) at android.view.View$PerformClick.run(View.java:24797) at android.os.Handler.handleCallback(Handler.java:790) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6626) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811) 表,但是当我通过SQLiteDB浏览器查看数据库的时候。

2 个答案:

答案 0 :(得分:1)

我认为您的主要问题是您使用了 CGRect

代替了 private static String DB_NAME ="test,db";// Database name

也就是说,您已经用逗号private static String DB_NAME ="test.db";// Database name而不是句点,进行了编码,因此资产文件夹中的数据库文件将不会被找到并且因此不会被复制。

由于使用 . ,首次运行文件 test,db 将导致创建数据库,它将为空,因此,在以后的运行中,将不会尝试在数据库存在时从资产文件夹中复制文件,因此,由于数据库为空,因此尝试访问该表将失败,因为该表不存在

  • 请注意,在大多数情况下,getRedableDatabase实际上将获得可写数据库
      

    创建和/或打开数据库。这将是返回的相同对象   通过getWritableDatabase()进行操作,除非出现某些问题,例如磁盘已满,   要求数据库以只读方式打开。在这种情况下,   将返回只读数据库对象。如果问题已解决,则   将来对getWritableDatabase()的调用可能会成功,在这种情况下,   只读数据库对象将关闭,而读/写对象   将来会退货。   getReadableDatabase

我相信使用this.getReadableDatabase();只是用来解决最初 databases 文件夹不存在,因此尝试从资产中复制文件的尝试失败的问题,因为父文件夹不存在。更好的解决方案是不使用getReadableDatabase,而是检查目录是否存在以及是否创建目录。

这种使用getReadableDatabase的问题在使用Android 9+时会带来更大的问题,因为默认情况下使用WAL(预先写入日志记录)会导致产生其他文件(数据库名称后缀-shm和-wal)

使用:-

getReabableDatabase

即使由于资产文件不存在而导致随后的复制失败,也无需使用//Check that the database exists here: /data/data/your package/databases/Da Name private boolean checkDataBase() { File dbFile = new File(DB_PATH + DB_NAME); if (dbFile.exists()) return true; if (!dbFile.getParentFile().exists()) dbFile.getParentFile().mkdirs(); return false; } 及其实际创建数据库文件所带来的复杂性。

要更加小心并应对-shm和-wal文件可能无意存在的可能性,则可以将上述内容扩展为:-

getReabableDatabase

通常不建议使用private boolean checkDataBase() { File dbFile = new File(DB_PATH + DB_NAME); if (dbFile.exists()) return true; if (!dbFile.getParentFile().exists()) dbFile.getParentFile().mkdirs(); if (new File(DB_PATH + DB_NAME + "-shm").exists()) new File(DB_PATH + DB_NAME + "-shm").delete(); if ((new File(DB_PATH + DB_NAME + "-wal")).exists()) new File(DB_PATH + DB_NAME + "-wal").delete(); return false; } ,而是建议使用更具体的DB_PATH = context.getApplicationInfo().dataDir + "/databases/";,因为不需要硬编码文件分隔符和文件夹名称。

下面这样的内容可能是一个更好的整体数据库助手:-

DB_PATH = mContext.getDatabasePath(DB_NAME).getPath();
  • 请注意查看整个代码中的注释

额外/测试

如果使用了上述方法(删除应用程序的数据或卸载应用程序以删除空数据库之后),但资产文件夹中没有合适的文件(test,db对于测试不变),则上述结果将导致更具解释性:-

public class DataBaseHelper extends SQLiteOpenHelper {
    private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
    //destination path (location) of our database on device
    private static String DB_PATH = "";
    private static String DB_NAME ="test.db";// Database name //<<<<<<<<<< CHANGED TO FIX PRIMARY ISSUE
    private SQLiteDatabase mDataBase;
    private final Context mContext;

    public DataBaseHelper(Context context)
    {
        super(context, DB_NAME, null, 1);// 1? Its database Version
        this.mContext = context;
        DB_PATH = mContext.getDatabasePath(DB_NAME).getPath();
    }

    public void createDataBase() throws IOException
    {
        //If the database does not exist, copy it from the assets.

        boolean mDataBaseExist = checkDataBase();
        if(!mDataBaseExist)
        {
            //this.getReadableDatabase(); //<<<<<<<<<< REMOVED (commented out)
            //this.close(); //<<<<<<<<<< REMOVED ()commented out
            try
            {
                //Copy the database from assests
                copyDataBase();
                Log.e(TAG, "createDatabase database created");
            }
            catch (IOException mIOException)
            {
                mIOException.printStackTrace(); //<<<<<<<<<< might as well include the actual cause in the log
                throw new Error("ErrorCopyingDataBase");
            }
        }
    }

    //Check that the database exists here: /data/data/your package/databases/Da Name
    private boolean checkDataBase()
    {
        File dbFile = new File(DB_PATH); //<<<<<<<<<< just the path used
        if (dbFile.exists()) return true; //<<<<<<<<<< return true of the db exists (see NOTE001)
        if (!dbFile.getParentFile().exists()) dbFile.getParentFile().mkdirs();
        if (new File(DB_PATH + "-shm").exists())
            new File(DB_PATH + "-shm").delete();
        if ((new File(DB_PATH + "-wal")).exists())
            new File(DB_PATH + "-wal").delete();
        return false;
    }

    /** NOTE001
     *  Just checking the file does leave scope for a non sqlite file to be copied from the assets folder
     *  and be copied resulting in an exception. The above could be extended to apply additional checks
     *  if considered required e.g. checking the first sixteen bytes for The header string: "SQLite format 3\000"
     */

    //Copy the database from assets
    private void copyDataBase() throws IOException
    {
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH; //<<<<<<<<<< just the path used
        OutputStream mOutput = new FileOutputStream(outFileName);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer))>0)
        {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    //Open the database, so we can query it
    public boolean openDataBase() throws SQLException
    {
        String mPath = DB_PATH;
        //Log.v("mPath", mPath);
        mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
        //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        return mDataBase != null;
    }

    /**
     * Note this can be added and the line uncommented (see below) to disable WAL logging which
     * from Anroid 9 (Pie) is the default
     */
    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);
        // db.disableWriteAheadLogging(); //<<<<<<<<<< uncomment if you want to not use WAL but use the less efficient joutnal mode.
    }

    @Override
    public synchronized void close()
    {
        if(mDataBase != null)
            mDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

如果应再次运行该应用程序而不进行任何更改,则上述情况也会发生,而不是出现更复杂的未找到表

注意,在运行上述代码之前,或者即使只是将test.db更改为test.db,也必须删除数据库文件。通过删除/清除应用程序的数据或卸载应用程序,可以轻松实现这一点。

以上已在Android 5.0(lollipop)(API 22)和Andorid 9(Pie)(API 28)上进行了测试,生成的Toast显示表(尽管为了方便起见,该表已从MASTER更改为sqlite_master (不必使用现有数据库文件创建数据库文件)。

答案 1 :(得分:0)

直接将数据路径设置为字符串,希望它可以工作

 private final static String DATABASE_PATH ="/data/data/com.yourpackagename/databases/";
public SQLiteDatabase openDatabase() throws SQLException
    {   String myPath = DATABASE_PATH + "DB_NAME";myDataBase = SQLiteDatabase.openOrCreateDatabase(myPath, null, null);
        return myDataBase;
    }`