创建表并将值插入数据库获取为nosuch表名

时间:2014-01-21 11:53:45

标签: android sqlite

创建表并将值插入数据库时​​获取为nosuch表名。 没有这样的表退出。请找到附加的logcat图像。所以如何在sqlite数据库中将值插入表中。

![在此处输入图片说明] [1]

  public class DataAdapter {

           DataBase database;
           SQLiteDatabase db;      

    public DataAdapter(Context context) {
        // TODO Auto-generated constructor stub
        database =new DataBase(context);    
    }

    public long insertData(String name ,String address){    

        SQLiteDatabase db= database.getWritableDatabase();  
        ContentValues values = new ContentValues();
        values.put(DataBase.NAME, name);
        values.put(DataBase.ADDRESS, address);
        return db.insert(DataBase.TABLENAME, null,values);
        }

    public static class DataBase extends SQLiteOpenHelper{

        public static final String DATABASE="Database.db";
        public static final String TABLENAME="tablename";   
        public static final int VERSION = 7;
        public static final String NAME="name"; 
        public static final String ADDRESS="address";
        public static final String ID="_id";

         public static final String CREATE_TABLE = "create table " + TABLENAME + "("+ 
     ID + " INTEGER PRIMARY KEY ," + NAME + " VARCHAR(255) ," + ADDRESS + "  VARCHAR(255) );";
        private Context context;

        public DataBase(Context context) {
            super(context, DATABASE, null, VERSION);        
            this.context =context;
            // TODO Auto-generated constructor stub     
            Toast.makeText(context, "onDataBase",Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL(CREATE_TABLE);

//      try {
//          Toast.makeText(context, "oncreate",Toast.LENGTH_SHORT).show();
//      
//      } catch (SQLException e) {
//          // TODO: handle exception
//      }       


        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            try {
                Toast.makeText(context, "oncUpgrade",Toast.LENGTH_SHORT).show();
                db.execSQL("DROP TABLE IF EXITS "+ TABLENAME);
                onCreate(db);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }   



    }

  [1]: http://i.stack.imgur.com/yWOtZ.jpg

1 个答案:

答案 0 :(得分:4)

onCreate()中存在SQL语法错误,您忽略了异常。由于onCreate()正常返回,因此父SQLiteOpenHelper认为一切正常。

具体来说,您需要IDINTEGER PRIMARY KEY之间的空格。当您决定自己捕获它们时,请记录您的异常。在onCreate()案例中,最好让异常冒出来。

更新onCreate()后,删除旧的数据库文件(卸载,清除数据等)或在代码中提升数据库版本,以便重新创建数据库。