文章目录
Difference between INT PRIMARY KEY and INTEGER PRIMARY KEY SQLite
Difference between INT PRIMARY KEY and INTEGER PRIMARY KEY SQLite
android.database.sqlite
包含 APP 用来管理自己的私有数据库的 SQLite 数据库管理类。
SQLite 的版本取决于 Android 的版本。见此表。
创建数据库类
- 必须重写 onCreate 和 onUpgrade 方法。
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
private static final String CREATE_BOOK = "create table Book (" +
"id integer primary key autoincrement, " +
"image integer, " +
"content text, " +
"title text, " +
"category text)";
private Context context;
public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK); // 创建新表
Toast.makeText(context, "Table Book Create succeeded", Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 删除重建新表
db.execSQL("drop table if exists Book");
onCreate(db);
}
}
当应用使用 SQLiteOpenHelper 实例通过 getWritableDatabase 调用 onCreate 创建新表后,如果又修改了旧表或添加了新表,重启应用并不会再次调用 onCreate 重新创建。这时除了卸载应用重装【手动滑稽】,只要提高数据库版本(即 SQLiteOpenHelper 实例的 version),即可通过 onUpgrade 进行更新。不过在此之前需要把旧表删除,不然直接报错。
查看创建情况(adb)
进入目录,输入 sqlite3 XXX.db 命令,再输入 .table 可以看到新表,输入 .schema 查看建表语句,输入 .quit 或 .exit 退出 sqlite 数据库的编辑
创建数据库操作类
查询(findAllBooksByCategory)和插入(saveBook):
public class SqlOperation {
private static MySQLiteOpenHelper mySQLiteOpenHelper;
// 获取数据库
public static void getDB(Context context,int version) {
mySQLiteOpenHelper = new MySQLiteOpenHelper(context, "BooksList.db", null, version);
mySQLiteOpenHelper.getWritableDatabase();
}
// 存入数据库
public static void saveBook(Book book) {
ContentValues contentValues = new ContentValues();
contentValues.put("content", book.getBook_content());