【问题标题】:Java - Android SQLite No Such Table ExistsJava - Android SQLite 不存在这样的表
【发布时间】:2022-03-17 23:01:00
【问题描述】:

我正在创建一个将查询数据库的应用程序,但是无法检测到表。

我已按照此博客中指示的步骤操作:http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

我制作了android_metadata表,复制到assets文件夹,创建了DataBaseHelper类,如下图:

public class DataBaseHelper extends SQLiteOpenHelper{
private static final String MedicalStaff = null;
private static final String Patients = null;

//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.angelo.thesis/databases/";

private static String DB_NAME = "androidHospital";

private SQLiteDatabase myDataBase; 

private final Context myContext;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 */
public DataBaseHelper(Context context) {

    super(context, DB_NAME, null, 1);
    this.myContext = context;
}   

/**
 * Creates a empty database on the system and rewrites it with your own database.
 * */
public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();

    if(dbExist){
        //do nothing - database already exist
    }else{

        //By calling this method and empty database will be created into the default system path
           //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            //throw new Error("Error copying database");
            System.out.println("Error copying database");

        }
    }

}

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){

        //database does't exist yet.

    }

    if(checkDB != null){

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws SQLException{

    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}

@Override
public synchronized void close() {
        if(myDataBase != null)
            myDataBase.close();

        super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

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

}

}

然后使用以下方法初始化此数据库助手:

DataBaseHelper myDbHelper = new DataBaseHelper(null);

onCreate 方法中:

myDbHelper = new DataBaseHelper(this);

    try {
        myDbHelper.createDataBase();
        System.out.println("Database Created!");
    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("Unable to create database");
    }


    try {
        myDbHelper.openDataBase();
        System.out.println("Database Opened!");
    } 
    catch (SQLException e) {
        // TODO Auto-generated catch block
        System.out.println("Unable to open database");
    }

try-catch 语句起作用,LogCat 显示 Created 和 Opened 消息。

然后通过这个函数进行查询: 字符串输入是用户输入,一个数字,用来寻找那个数字对应的人。

public String searchStaff(DataBaseHelper myDB, String input){

    System.out.println("searchStaff entered");

    String data = null;
    Cursor cursor = null;
    SQLiteDatabase db = myDB.getReadableDatabase();

    //int myNum = Integer.parseInt(input);

    try{
        cursor = db.rawQuery("SELECT LastName, FirstName FROM MedicalStaff WHERE _id =" + input, null);

    }   
    catch(Exception e){
    }

    if( cursor != null ){
        cursor.moveToFirst();

        data = cursor.getString(cursor.getColumnIndexOrThrow("LastName")) + " " +
                cursor.getString(cursor.getColumnIndex("FirstName"));   
        cursor.close();
    }

    System.out.println("Data: " + data);
    return data;

}

但是,显示的数据变成了null,Log Cat 告诉我表MedicalStaff 不存在。

我觉得我在这里错过了一些非常基本的东西。 谢谢大家的帮助。

【问题讨论】:

    标签: android sqlite android-cursor


    【解决方案1】:

    更改这行代码

    `DataBaseHelper myDbHelper = new DataBaseHelper(null);

    DataBaseHelper myDbHelper = new DataBaseHelper(this);

    这是因为您创建了一个带有 null 的 Databasehelper 对象。所以用指定的上下文创建。

    【讨论】:

    • @Razgriz 您是否检查过数据库是否是在您的 sqlite 数据库浏览器中使用该表创建的。确保您没有两次初始化数据库对象。
    • 是的,它已创建。我也尝试查询另一个表,但似乎找不到。
    • 好的。您是否检查过使用MedicalStaff 创建的表名。你能更新表创建的编码吗?
    • 我认为我在创建数据库时做错了。我尝试添加一个不同的数据库并进行搜索,结果成功了。
    • 哦。高超。如果您发现我的答案对您有所帮助,请接受它作为答案。所以其他人会知道你得到了答案。快乐编码
    【解决方案2】:

    我认为数据库创建成功。但表创建未完成。请检查..

    【讨论】:

    • @Razgiz 请阅读在developer.android.com/tools/help/adb.html#sqlite中从远程外壳检查 sqlite3 数据库
    • 这是否也适用于由 SQLite 数据库浏览器创建的数据库?您提供的链接似乎涵盖了由 android 应用程序创建的数据库。
    【解决方案3】:

    更改这行代码

    DataBaseHelper myDbHelper = new DataBaseHelper(null);
    

    DataBaseHelper myDbHelper;
    

    如果您初始化 DataBaseHelper,然后将 null 作为参数传递,Database Helper 将无法获取 Context 并会导致您现在面临的意外行为。因此,如上所述更改您的代码并尝试。希望它对你有用。

    【讨论】:

      【解决方案4】:

      new DataBaseHelper(null); 看起来不太好。您应该使用有效的上下文对其进行初始化

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-12
        • 1970-01-01
        • 2019-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-20
        相关资源
        最近更新 更多