直接进入要说的主题:
数据库的操作借助于 SQLiteOpenHelper,SQLiteOpenHelper 是一个抽象类,我们我们在使用 SQLiteOpenHelper 时要先创建一个 MySQLiteOpenHelper 继承 SQLiteOpenHelper 类。
SQLiteOpenHelper 有两个非常重要的方法:getReadableDatabase() 方法返回数据库是一个只读的;getWriteableDatabase() 方法获得是一个可读写的数据库对象。这里我们使用 getWriteableDatabase() 方法获得数据库 Database 对象。
首先看下要实现的效果
接下来是目录结构示意图
1.activity_main.xml 页面定义所有的按钮控件。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/btCreate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="Create database" />
<Button
android:id="@+id/btAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/btCreate"
android:layout_marginTop="30dp"
android:text="Add data" />
<Button
android:id="@+id/btUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/btAdd"
android:layout_marginTop="20dp"
android:text="Update_data" />
<Button
android:id="@+id/btDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/btUpdate"
android:layout_marginTop="20dp"
android:text="Delete_Date" />
<Button
android:id="@+id/btQuery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btDelete"
android:layout_marginTop="20dp"
android:text="Query_data" />
</RelativeLayout>
2.MainActivity.java 页面用于将增删改查方法和按钮绑定。
public class MainActivity extends AppCompatActivity {
private Button btCreate, btAdd, btUpdate, btDelete, btQuery;
private PersonDaoImpl personDaoImpl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
personDaoImpl = new PersonDaoImpl(SQLiteTestActivity.this);
/* 创建 */
btCreate = (Button) findViewById(R.id.btCreate);
btCreate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MySQLiteOpenHelper myDatabaseHelper = new MySQLiteOpenHelper(SQLiteTestActivity.this);
myDatabaseHelper.getWritableDatabase();
Toast.makeText(SQLiteTestActivity.this, "Create succeeded", Toast.LENGTH_SHORT).show();
}
});
/* 添加 */
btAdd = (Button) findViewById(R.id.btAdd);
btAdd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 10000; i < 10011; i++) {
if (personDaoImpl.queryOne(i + "")) {
Log.i("SQLiteTestActivity", "第" + i + "个小明存在");
} else {
Person person = new Person("" + i, "第" + i + "个小明", "head_201708291" + i);
personDaoImpl.add(person);
}
}
Toast.makeText(SQLiteTestActivity.this, "Add Succeed", Toast.LENGTH_SHORT).show();
}
});
/* 修改 */
btUpdate = (Button) findViewById(R.id.btUpdate);
btUpdate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (personDaoImpl.queryOne("10001")) {
Log.i("SQLiteTestActivity", "第10001个小明存在");
Person person = new Person("10001", "修改过后的小明", "http://img2.woyaogexing.com/2017/09/04/07b44481e320ba7b!300x300_big.jpg");
personDaoImpl.update(person);
Toast.makeText(SQLiteTestActivity.this, "Update Succeed", Toast.LENGTH_SHORT).show();
}
}
});
/* 删除 */
btDelete = (Button) findViewById(R.id.btDelete);
btDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (personDaoImpl.queryOne("10000")) {
personDaoImpl.delete("10000");
Toast.makeText(SQLiteTestActivity.this, "Delete Succeed", Toast.LENGTH_SHORT).show();
} else {
Log.i("SQLiteTestActivity", "第10000个小明不存在");
}
}
});
/* 查询 */
btQuery = (Button) findViewById(R.id.btQuery);
btQuery.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
List<Person> persons = personDaoImpl.query();
Log.i("SQLiteTestActivity", "----- 查询所有 ---begin--");
for (Person person : persons) {
Log.i("SQLiteTestActivity", person.toString());
}
Log.i("SQLiteTestActivity", "----- 查询所有 ---end--");
Toast.makeText(SQLiteTestActivity.this, "Query Succeed", Toast.LENGTH_SHORT).show();
}
});
}
3.定义 Person.java 实体类并重写 toString 方法,用于查询时数据的输出。
public class Person {
private int id;
private String userId;//用户Id
private String avatarreName;//头像
private String nickName;//昵称
public Person() {}
public Person(String userId, String avatarreName, String nickName) {
this.userId = userId;
this.avatarreName = avatarreName;
this.nickName = nickName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getAvatarreName() {
return avatarreName;
}
public void setAvatarreName(String avatarreName) {
this.avatarreName = avatarreName;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
}
4. 定义 BookDao.java 接口页面用于定义父类方法。
public interface PersonDao {
public boolean queryOne(String userId);
public long add(Person person);
public int delete(String userId);
public void update(Person person);
public List<Person> query();
}
5.定义 MySQLiteOpenHelper.java 页面用于继承 SQLiteOpenHelper 类,进行创建数据库。这里为了方便直接在本类中写,最好单独写一个config类。
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
private static final String DB_NAME="person.db";// 数据库名称
private static final int DB_VERSION=1;// 版本号
public static final String TABLE_NAME="person";// 表名
public static final String CUSTOMER_ID="id";
public static final String PERSON_ID="userId";
public static final String PERSON_NAME="nickName";
public static final String PERSON_PORTRAIT="portrait";
private static MySQLiteOpenHelper helper;
public MySQLiteOpenHelper(Context context) {
super(context,DB_NAME,null,DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//在创建数据库时,初始化创建数据库中包含的数据库表。这里以一个“人物”的数据表为例
/*
* Person 创建 "人物"数据表
*/
sqLiteDatabase.execSQL("create table if not exists " + TABLE_NAME + "("
+ CUSTOMER_ID + " Integer not null primary key autoincrement,"
+ PERSON_ID + " verchar(10),"
+ PERSON_NAME + " verchar(20),"
+ PERSON_PORTRAIT + " verchar(150))");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//用于升级数据库,只需要在创建本类对象时传入一个比之前创建传入的version大的数即可。
}
}
6.定义 PersonDaoImpl.java 页面用于实现 PersonDao.java 接口,重写 PersonDao.java 页面中的增删改查方法。
public class PersonDaoImpl implements PersonDao{
MySQLiteOpenHelper myDatabaseHelper;
public PersonDaoImpl(Context context){
myDatabaseHelper=new MySQLiteOpenHelper(context);
}
/**
* 新增一条
* @param person
* @return 返回的是数据的 id,如果返回 - 1 时表示未添加成功
*/
@Override
public long add(Person person) {
SQLiteDatabase db=myDatabaseHelper.getWritableDatabase();
ContentValues values=new ContentValues();
// 开始组装数据
values.put(MySQLiteOpenHelper.PERSON_ID,person.getUserId());
values.put(MySQLiteOpenHelper.PERSON_NAME,person.getNickName());
values.put(MySQLiteOpenHelper.PERSON_PORTRAIT,person.getAvatarreName());
//id 返回的是数据的 id,如果返回 - 1 时表示未添加成功
long id=db.insert(MySQLiteOpenHelper.TABLE_NAME,null,values);// 插入数据
values.clear();
db.close();
return id;
}
/* 查询是否含有 */
@Override
public boolean queryOne(String userId) {
SQLiteDatabase db = myDatabaseHelper.getReadableDatabase();
Cursor cursor=db.query(MySQLiteOpenHelper.TABLE_NAME,null,
MySQLiteOpenHelper.PERSON_ID+"=?",new String[]{userId},null,null,null);
boolean b = cursor.moveToNext();
cursor.close();
db.close();
return b;
}
/* 根据页码数目删除信息 */
@Override
public int delete(String userId) {
SQLiteDatabase db=myDatabaseHelper.getWritableDatabase();
//i 返回的是删除的是第几行的数据,返回 0 表示删除不成功
int i = db.delete(MySQLiteOpenHelper.TABLE_NAME,
MySQLiteOpenHelper.PERSON_ID + "=?",new String[]{String.valueOf(userId)});
db.close();
//i 返回的是删除的是第几行的数据,返回 0 表示删除不成功
return i;
}
/* 根据userId修改信息 */
@Override
public void update(Person person) {
SQLiteDatabase db=myDatabaseHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(MySQLiteOpenHelper.PERSON_ID,person.getUserId());
values.put(MySQLiteOpenHelper.PERSON_NAME,person.getNickName());
values.put(MySQLiteOpenHelper.PERSON_PORTRAIT,person.getAvatarreName());
db.update(MySQLiteOpenHelper.TABLE_NAME,values,
MySQLiteOpenHelper.PERSON_ID + "=?",new String[]{String.valueOf(person.getUserId())});
values.clear();
db.close();
}
/* 查询信息,使用 List 返回 */
@Override
public List<Person> query() {
List<Person> persons=null;
SQLiteDatabase db=myDatabaseHelper.getReadableDatabase();// 查询是 Readable,其余是 Writable
Cursor cursor=db.query(MySQLiteOpenHelper.TABLE_NAME,null,null,null,null,null,null);
if(cursor!=null){
persons=new ArrayList<Person>();
while(cursor.moveToNext()){
int id=cursor.getInt(cursor.getColumnIndex(myDatabaseHelper.CUSTOMER_ID));
String userId=cursor.getString(cursor.getColumnIndex(MySQLiteOpenHelper.PERSON_ID));
String nickName=cursor.getString(cursor.getColumnIndex(MySQLiteOpenHelper.PERSON_NAME));
String avatarre=cursor.getString(cursor.getColumnIndex(MySQLiteOpenHelper.PERSON_PORTRAIT));
Person person=new Person(userId,nickName,avatarre);
persons.add(person);
}
}
cursor.close();
db.close();
return persons;
}
}
代码以上。
最后程序运行就可以显示效果了。
点击不同的按钮,可分别对数据库进行不同的操作并输出 Toast 提示和 LogCat 日志信息。