关于Android中DatabaseHelper和Database的关系
简单来说,DatabaseHelper 可以看成是 Database 的工厂类。
想得到Database,需要首先得到一个DatabaseHelper的对象,得到的方法很简单,直接使用new就可以了,会自动调用DatabaseHelper的构造方法,构造方法传入的参数分别是 (Context,数据库名,一般为null的值,版本号),注意此时虽然传入了数据库名,但是并没有实际创建数据库。
然后使用helper中的getWritableDatabase即可,此处如果是对getWritableDatabase的第一次调用,那么程序会创建相应的数据库,并自动调用onCreate方法。(所以说onCreate方法中的create,指的既不是DatabaseHelper的创建,也不是表的创建,而是数据库的创建。) 所以一般建议在onCreate中加入创建表的语句,也就是创建了数据库之后,马上创建相应的表,这也很符合一般人的逻辑。
粗略画了一个uml图,可能不是很严谨
package com.example.t11;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button1;
Button button2;
MyDatabaseHelper MyDBHelper;
SQLiteDatabase MyDB;
Boolean continued;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
continued=true;
MyDBHelper=new MyDatabaseHelper(this,"T11.db",null,1);//得到helper
button1=findViewById(R.id.button1);
button2=findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1://点击按钮1之后,从databaseHelper那里得到相应的database
MyDB=MyDBHelper.getWritableDatabase();
//以下是关于插入数据的操作,不重要
ContentValues values=new ContentValues();
while (continued==true){
values.put("content","hello");
values.put("time",new Date().toLocaleString());
MyDB.insert("t11",null,values);
SystemClock.sleep(2000);
}
//以上是关于插入数据的操作,不重要
case R.id.button2:
continued=false;
}
}
class MyDatabaseHelper extends SQLiteOpenHelper {
Context mContext;
private final String CREATE_BOOK="create table t11("+
"content text ,"+
"time text)";
public MyDatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);//databaseHelper 的构造函数
//构造函数的四个参数分别是 context , 数据库名, null, 版本号
mContext=context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_BOOK);//在创建好数据库之后,马上在数据库里创建表
Toast.makeText(MainActivity.this,"创建成功",Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
}