Android数据库:插入查询错误

时间:2013-12-29 18:39:13

标签: android database sqlite

我正在开发一个需要持久性功能的应用程序。由于我的理解有限,因此需要两个类 - SQLiteHelper类& DatabaseManager类。

为了让事情发生变化,我有一个简单的过程,它将采用单个文本输入并将其插入数据库。但是,我收到一个错误:

  

12-29 19:17:47.952:E / SQLiteDatabase(5840):android.database.sqlite.SQLiteException:没有这样的表:UserTable(代码1):,同时编译:INSERT INTO UserTable(用户名)VALUES(? )

暗示没有用户表,但是当调用onCreate()时,应该创建此表。

对于帮助克服这一障碍的任何帮助,我都会非常感激。以下是用于创建数据库功能的两个类。非常感谢。

  

公共类DatabaseHelper扩展了SQLiteOpenHelper {

private static final String DATABASE_NAME         = "NutrtionIntuition";
private static final int  DATABASE_VERSION    = 2;

// Database creation sql statement
private static final String DATABASE_CREATE =   "create table UserTable " +
                                                "( _id integer primary key,name text not null);";

public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Method is called during creation of the database. Method is also called on upgrade of database?
@Override
public void onCreate(SQLiteDatabase database) {
            database.execSQL(DATABASE_CREATE);
}

// Method is called during an upgrade of the database,
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {

                database.execSQL("DROP TABLE IF EXISTS User");
                onCreate(database);
} }
public class DatabaseManager{  

    private DatabaseHelper      dbHelper;  
    private SQLiteDatabase      database;  

    private static final String     USER_TABLE          = "UserTable";

    public static final String      KEY_ROWID           = "_id";
    public static final String      KEY_USERNAME        = "username";


    public DatabaseManager(Context context){  
      dbHelper = new DatabaseHelper(context);  
      database = dbHelper.getWritableDatabase();  
    }

    //Insert Records into the User Table
    public long insertRecords(int id, String name){  
        ContentValues values = new ContentValues();  
        //values.put(KEY_ROWID , id);  
        values.put(KEY_USERNAME, name); 
        Log.v("Test","Inserting.....");

        return database.insert(USER_TABLE, null, values);  
    }   

    public Cursor selectRecords() {
         String[] cols = new String[] {KEY_ROWID, KEY_USERNAME};  
         Cursor mCursor = database.query(true, USER_TABLE,cols,null  
              , null, null, null, null, null);  
         if (mCursor != null) {  
          mCursor.moveToFirst();  
       }  
       return mCursor; // iterate to get each value.
    }
}

1 个答案:

答案 0 :(得分:0)

您正在创建一个包含_idname的表格,而在插入时您正在使用_idusername。还有一项 - onUpgradeDROP TABLE IF EXISTS User应为DROP TABLE IF EXISTS UserTable