知识点整理(一)SQLite有关知识
发布时间:2020-12-12 18:58:08 所属栏目:百科 来源:网络整理
导读:发现不整理自己忘记的非常快…… 先写写吧 文件存储 在第六章也有,但只是一些简单的键值对,shared。。。也是所以就需要数据库 (不过此处大概都是存在本地的哦~) 1.基础知识 (1) SQLiteOpenHelper帮助类,是个抽象类,用的时候继承onCreate() OnUpgrade
发现不整理自己忘记的非常快…… 先写写吧
文件存储 在第六章也有,但只是一些简单的键值对,shared。。。也是所以就需要数据库 (不过此处大概都是存在本地的哦~)
1.基础知识
(1) SQLiteOpenHelper帮助类,是个抽象类,用的时候继承onCreate() OnUpgrade()。getReadableDatabase() 和getWritableDatabase() 。后者在磁盘已满的时候会异常
(2)构造方法,一般用接受4个那个就好。第一个参数是Context,第二个参数是数据库名,第三个参数允许我们在查询数据的时候返回一个自定义的Cursor,一般都是传入null 。第四个参数表示当前数据库的版本号。这样就有了
实例,调用上面那两个get方法就可以创建数据库了~~
2.实例
sql建表语句先写出来。此处示范这种:(代码折叠)
create table Book (
? ? id integer primary key autoincrement,
? ? author text,
? ? price real,
? ? pages integer,
? ? name text)
下面是完整代码。
(1)把建表语句写进了字符串常量,不过!注意加号和引号好多哦,这种作为字符串处理的,字符串声明为final和static
(2)这个helper类的,构造函数~ 看起来是把mContext继承出来啦~ (注意那四个参数的构造参数都是啥)
(3)在onCreate方法里~ 传入SQLiteDataBase对象,对建库语句 execSQL, 就建立完成啦~ (跳出toast提示,toast继承了那个context,然后一句话,然后short)
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)";
?
? ? 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);
? ? ? ? Toast.makeText(mContext,"Create succeeded",Toast.LENGTH_SHORT).show();
? ? }
?
? ? @Override
? ? public void onUpgrade(SQLiteDatabase db,int?
oldVersion,int newVersion) {
? ? }
}
(4)还没完哦,在xml里添加了Button,在main里还要写几句真的把它实现:
下面1 新建了一个helper实例2 通过构造函数实例化 3 getwirteable。。至此就完成啦~?
?
dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,1);
? ? ? ? Button createDatabase = (Button) findViewById(R.id.create_database);
? ? ? ? createDatabase.setOnClickListener(new View.OnClickListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onClick(View v) {
? ? ? ? ? ? ? ? dbHelper.getWritableDatabase();
? ? ? ? ? ? }
? ? ? ? });
3.升级数据库
(1)这样呢,在helper类里还是那三步,字符串常量,构造,然后execSQL,但是如果在上一个实验的基础上来,已经建库了就不能再建立,除非卸载。所以就需要update~
但是这样是不好的吧,删除表之后岂不是都没了
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);
? ? }
(2)那我们来百度一下。如何百度呢??
我百度常常是无效的,有谷歌也一样。。那先解析一下,我到底遇到了什么问题?
首先明确,drop是删除了表。搜索drop table if exist,确定这个语句的确是删除了表,和表里的数据;所以感觉是安卓的问题,update只能这么用吗
搜了一下,问了一下群里的大哥,那是偷懒行为……
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |