6.4 SQLite数据库存储

6.4.1 创建数据库

SQLiteOpenHelper帮助类让我们能够更加方便的管理数据库。抽象类,需自己创建帮助类继承他。
SQLiteOpenHelper的构造器:  Cursor一般为null
Public Constructors
SQLiteOpenHelper( Context context,  String name,  SQLiteDatabase.CursorFactory factory, int version)
Create a helper object to create, open, and/or manage a database.
SQLiteOpenHelper( Context context,  String name,  SQLiteDatabase.CursorFactory factory, int version,  DatabaseErrorHandler errorHandler)
Create a helper object to create, open, and/or manage a database.

两个抽象方法:onCreate()和onUpgrade();
两个重要的实例方法:
1.
public SQLiteDatabase getReadableDatabase ()
Added in  API level 1

Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem, such as a full disk, requires the database to be opened read-only. In that case, a read-only database object will be returned. If the problem is fixed, a future call to getWritableDatabase() may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future.

Like getWritableDatabase(), this method may take a long time to return, so you should not call it from the application main thread, including from ContentProvider.onCreate().

Returns
SQLiteDatabase a database object valid until getWritableDatabase() or close() is called.
Throws
SQLiteException if the database cannot be opened
2.
public SQLiteDatabase getWritableDatabase ()
Added in  API level 1

Create and/or open a database that will be used for reading and writing. The first time this is called, the database will be opened and onCreate(SQLiteDatabase)onUpgrade(SQLiteDatabase, int, int) and/oronOpen(SQLiteDatabase) will be called.

Once opened successfully, the database is cached, so you can call this method every time you need to write to the database. (Make sure to call close() when you no longer need the database.) Errors such as bad permissions or a full disk may cause this method to fail, but future attempts may succeed if the problem is fixed.

Database upgrade may take a long time, you should not call this method from the application main thread, including from ContentProvider.onCreate().

Returns
SQLiteDatabase a read/write database object valid until close() is called
Throws
SQLiteException if the database cannot be opened for writing



我们希望能创建一个名为BookStore.db的数据库,然后在这个数据库中新建一张BOOK表,表中有ID(主键)、作者、价格、页数和书名等列。BOOK表的建表语句如下
   
   
create table Book (
id integer primary key autoincrement,//integer表示整形,real表示浮点型,text表示文本类型,blob表示二进制类型、
//使用primary key 将ID设为主键,并用autoincrement表示id列是自增长的
author text,
price real,
pages integer,
name text)
新建MyDatabaseHelper类继承自SQLiteOpenHelper,代码如下
    
    
package com.example.databasetest;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
 
/**
* Created by 孙伟 on 30/03/2016.
*/
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) {
}
}
关于execSQL
public void execSQL (String sql)
Added in  API level 1

Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

It has no means to return any data (such as the number of affected rows). Instead, you're encouraged to use insert(String, String, ContentValues)update(String, ContentValues, String, String[]), et al, when possible.

When using enableWriteAheadLogging(), journal_mode is automatically managed by this class. So, do not set journal_mode using "PRAGMA journal_mode'" statement if your app is using enableWriteAheadLogging()

Parameters
sql String: the SQL statement to be executed. Multiple statements separated by semicolons are not supported.
Throws
SQLException if the SQL string is invalid

之后修改activity_main.xml中的代码如下:
    
    
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/create_database"/>
</LinearLayout>

新建了一个按钮用于创建数据库,最后修改Mainactivity中的代码 如下:
     
     
package com.example.databasetest;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends AppCompatActivity {
 
private MyDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 数据库名定为BookStore.db,版本号为1,
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) {
// 第一次点击 Create database按钮时会检测没有这个数据库
dbHelper.getWritableDatabase();
}
});
}
}
Book表的内容可以通过adb shell方式来进行检查
adbshell可以直接对连接在电脑上的手机或模拟器进行调试操作。


6.4.2升级数据库
之前的程序onUpgrade方法留空没写,它适用于对数据库进行升级。
如果还想再添加一张Category表用于记录书籍的分类可以这么做。
建表语句如下:
     
     
create table Category {
id integer primary key autoincrement,
category_name text,
category_code integer)
接下来将这条建表语句添加到MydatabaseHelper中,代码如下
     
     
package com.example.databasetest;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
 
/**
* Created by 孙伟 on 30/03/2016.
*/
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) {
}
}

由于之前BookStore.db已经存在所以此时运行并不会有Toast提示。
那么想要添加一张新表,可以采用SQLiteOpenHelper的升级功能。代码如下
     
     
@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);
}
两条DROP语句判断如果这两个表存在就在就删除掉 ,然后在调用onCreate()方法重新创建。
那么新的数据库版本号应该比原来的1要大
     
     
//新的数据库名定为BookStore.db,版本号为2
dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);
重新运行点击按钮,发现数据库生成成功了
进入adb shell观察发现确实创建成功了
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值