xiaozezezeze 2018-09-07 12:05 采纳率: 0%
浏览 1767
已结题

使用Android中的SQLite建立一个数据库,加了一张Book表,增加一个表,升级数据库失败

使用Android中的SQLite建立一个数据库BookStore,加了一张Book表,然后我要增加一个Category表,按照《第一行代码》中的6.4.2所示代码写完后,点击App后直接闪退。(我用的是Andro Studio3.1版本,使用真机开发,系统Androi8.1)。代码如下

主活动代码:
public class MainActivity extends AppCompatActivity {

private MyDatabaseHelper dbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    dbHelper=new MyDatabaseHelper(this,"BookStore.db",null,2);
    Button createDatabase=(Button)findViewById(R.id.create_database);
    createDatabase.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dbHelper.getWritableDatabase();
        }
    });
}

}

定义一个数据库类MyDatabaseHelper继承SQLiteOpenHelper
public class MyDatabaseHelper extends SQLiteOpenHelper {

public static final String CREATE_BOOK="create table Book("
        +"id integer primary key autoincrement,"
        +"author text"
        +"price real"
        +"pages integer"
        +"name text)";

public static final String CREATE_CATEGORY="create table Category("
        +"id integer primary key autoincrement"
        +"category_name text"
        +"category_code integer)";

private Context mContext;
public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){
    super(context,name,factory,version);
    mContext=context;
}
@Override
public void onCreate(SQLiteDatabase db){
    db.execSQL(CREATE_BOOK);
    db.execSQL(CREATE_CATEGORY);
    Toast.makeText(mContext,"Create succeeded",Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
    db.execSQL("drop table if exists Book");
    db.execSQL("drop table if exists Category");
    onCreate(db);

}

}

  • 写回答

3条回答 默认 最新

  • threenewbee 2018-09-07 15:49
    关注

    public static final String CREATE_CATEGORY="create table Category("
    +"id integer primary key autoincrement,"
    +"category_name text,"
    +"category_code integer)";

    目测缺少2个逗号,是不是有别的问题,你调试下。

    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R