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个逗号,是不是有别的问题,你调试下。

    评论

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器