简体   繁体   English

Android sqlite列未找到错误

[英]Android sqlite column not found error

Ok so I have made the usual Database Helper class as shown below. 好的,所以我制作了通常的Database Helper类,如下所示。 I've also made a class which uses the getData and insertData methods with another class to get specific things, for example with my User class to get User name. 我还创建了一个类,该类使用getData和insertData方法以及另一个类来获取特定内容,例如,使用我的User类来获取用户名。 However, when calling that Controller class in my main activity I want to use it in, it tells me that the columns I try access don't exist. 但是,在我的主要活动中调用该Controller类时,我想在其中使用它,它告诉我尝试访问的列不存在。 I've been trying at this for hours now and am getting tired... 我已经尝试了几个小时,现在已经累了...

in logcat is says... sqlite returned: 在logcat中说... sqlite返回:

error code = 1, msg = table userinfo has no column named username

Also I have added stuff like _id and android_metadata to my database. 另外,我还向数据库中添加了_idandroid_metadata类的东西。 Thanks. 谢谢。

    public class DatabaseHelper extends SQLiteOpenHelper{

            //The Android's default system path of your application database.
            private static final String DB_PATH = "/data/data/com.cslearn/databases/";
            private static final String DB_NAME = "example.db";
            private static final int DB_VERSION = 1; 
            private final Context myContext;
            private SQLiteDatabase myDatabase;

            public DatabaseHelper(Context context) {
                super(context, DB_NAME, null, DB_VERSION);
                this.myContext = context;
                System.out.println(context.getDatabasePath("myDatabase"));
            }   
            public void createDataBase() throws IOException{
                System.out.println("database creating...");
                boolean dbExist = checkDataBase();

                if(dbExist){
                    //do nothing - database already exist
                    System.out.println("db exists");
                }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();
                    System.out.println("path = "+this.getReadableDatabase().getPath());
                    System.out.println("get database");

                    try {
                        this.close();
                        copyDataBase(); 
                    } catch (IOException e) {
                        throw new Error("Error copying database");
                    }
                }
                System.out.println("database created");
                this.close();
            }
            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;
            }
            private void copyDataBase() throws IOException{


                System.out.println("Copying database....");
                //Open your local db as the input stream
                InputStream myInput = myContext.getAssets().open(DB_NAME);
                System.out.println("input > get assets");
                // 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);
                    System.out.println("output write...");

                }
                System.out.println("Database copied!!");
                //Close the streams
                myOutput.flush();
                myOutput.close();
                myInput.close();

            }
         /**   public void openReadonlyDataBase() throws SQLException{

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

            }*/
            public void openDataBase() throws SQLException{
                String myPath = DB_PATH + DB_NAME;
                myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
            }

            @Override
            public synchronized void close() {

                    if(myDatabase != null)
                        myDatabase.close();

                    super.close();
            }


            public void insertData (String sql){
                try {
                    this.createDataBase();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    this.openDataBase();
                    System.out.println("database opened");
                }catch(SQLException e){

                    throw e;

                }
                myDatabase.execSQL(sql); //separate values with ,
                this.close();
            }



            public ArrayList<String> getData (String table,String [] columns, String selection){
                try {
                    this.createDataBase();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    this.openDataBase();
                    System.out.println("database opened");

                }catch(SQLException e){
                    throw e;
                }
                System.out.println("getting data");
                ArrayList<String> results = new ArrayList<String>();
                Cursor c = myDatabase.query(table, columns, selection, null, null, null, null);
                System.out.println(c.getColumnCount());
                System.out.println(c.getColumnNames());
                System.out.println("got cursor c");     
                     if (c != null) {
                         /* Check if at least one Result was returned. */
                         if (c.moveToFirst()) {
                                 do {
                                         /* Retrieve the values of the Entry
                                          * the Cursor is pointing to. */
                                            String[] row = new String[c.getColumnCount()];      
                                            for(int i=0; i<c.getColumnCount(); i++){    
                                               row[i] = c.getString(i);
                                               System.out.println("getting data");
                                               results.add(row[i]);
                                               System.out.println("adding string");
                                    }

                                 } while (c.moveToNext());
                         }
                     }
                close();
                return results;
            }
            @Override
            public void onCreate(SQLiteDatabase db) {
            }
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            }

                // Add your public helper methods to access and get content from the database.
               // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
               // to you to create adapters for your views.
}

You have overriden the onCreate(SQLiteDatabase db) method but it doesn't do anything. 您已经重写了onCreate(SQLiteDatabase db)方法,但是它没有任何作用。 You need to create your tables in this method like so: 您需要使用以下方法创建表:

// SQL statements to create new tables.
private static final String TBL_FRIENDS = "friends";
private static final String CREATE_TABLE_FRIENDS = "create table " +
    TBL_FRIENDS + " (" + KEY_ID + " integer primary key autoincrement, " +
    FRIEND_ID + " integer not null, " + FRIEND_MARKER + " integer not null, " +
    FRIEND_MOBILE + " text not null, " + FRIEND_NAME + " text not null);";

@Override
    public void onCreate(SQLiteDatabase db)
    {           
        db.execSQL("DROP TABLE IF EXISTS " + TBL_FRIENDS);          
        db.execSQL(CREATE_TABLE_FRIENDS);           

    }

The other static strings shown eg KEY_ID are column names which are used in other methods. 显示的其他静态字符串(例如KEY_ID)是在其他方法中使用的列名。

You should put some code in onCreate() and onUpgrade() . 您应该在onCreate()onUpgrade()放入一些代码。

onCreate() is called when the database is created for the first time. 首次创建数据库时,将调用onCreate() onUpgrade() is called when the database version is increased. 数据库版本增加时,将调用onUpgrade()

Example use of onCreate() and onUpgrade() onCreate()onUpgrade()示例用法

  • onCreate(SQLiteDatabase db) executes SQL commands that creates tables. onCreate(SQLiteDatabase db)执行创建表的SQL命令。
  • onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) executes SQL commands that drops tables (if exists) then call onCreate() (so that the table will have the new structure). onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)执行删除表的SQL命令(如果存在),然后调用onCreate() (这样表将具有新结构)。

Don't forget to increment DB_VERSION whenever you want to onUpgrade to be called. 每当您要调用onUpgrade时,请不要忘记增加DB_VERSION

您是否将DEFAULT VALUES分配给表的列名?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM