直接進(jìn)入要說的主題:
數(shù)據(jù)庫的操作借助于 SQLiteOpenHelper,SQLiteOpenHelper 是一個(gè)抽象類窃肠,我們我們?cè)谑褂?SQLiteOpenHelper 時(shí)要先創(chuàng)建一個(gè) MySQLiteOpenHelper 繼承 SQLiteOpenHelper 類。
SQLiteOpenHelper 有兩個(gè)非常重要的方法:getReadableDatabase() 方法返回?cái)?shù)據(jù)庫是一個(gè)只讀的稠肘;getWriteableDatabase() 方法獲得是一個(gè)可讀寫的數(shù)據(jù)庫對(duì)象覆劈。這里我們使用 getWriteableDatabase() 方法獲得數(shù)據(jù)庫 Database 對(duì)象。
首先看下要實(shí)現(xiàn)的效果
接下來是目錄結(jié)構(gòu)示意圖
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);
/* 創(chuàng)建 */
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 + "個(gè)小明存在");
} else {
Person person = new Person("" + i, "第" + i + "個(gè)小明", "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個(gè)小明存在");
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個(gè)小明不存在");
}
}
});
/* 查詢 */
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 實(shí)體類并重寫 toString 方法天试,用于查詢時(shí)數(shù)據(jù)的輸出槐壳。
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 類喜每,進(jìn)行創(chuàng)建數(shù)據(jù)庫务唐。這里為了方便直接在本類中寫,最好單獨(dú)寫一個(gè)config類带兜。
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
private static final String DB_NAME="person.db";// 數(shù)據(jù)庫名稱
private static final int DB_VERSION=1;// 版本號(hào)
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) {
//在創(chuàng)建數(shù)據(jù)庫時(shí)枫笛,初始化創(chuàng)建數(shù)據(jù)庫中包含的數(shù)據(jù)庫表。這里以一個(gè)“人物”的數(shù)據(jù)表為例
/*
* Person 創(chuàng)建 "人物"數(shù)據(jù)表
*/
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) {
//用于升級(jí)數(shù)據(jù)庫刚照,只需要在創(chuàng)建本類對(duì)象時(shí)傳入一個(gè)比之前創(chuàng)建傳入的version大的數(shù)即可刑巧。
}
}
6.定義 PersonDaoImpl.java 頁面用于實(shí)現(xiàn) PersonDao.java 接口,重寫 PersonDao.java 頁面中的增刪改查方法无畔。
public class PersonDaoImpl implements PersonDao{
MySQLiteOpenHelper myDatabaseHelper;
public PersonDaoImpl(Context context){
myDatabaseHelper=new MySQLiteOpenHelper(context);
}
/**
* 新增一條
* @param person
* @return 返回的是數(shù)據(jù)的 id海诲,如果返回 - 1 時(shí)表示未添加成功
*/
@Override
public long add(Person person) {
SQLiteDatabase db=myDatabaseHelper.getWritableDatabase();
ContentValues values=new ContentValues();
// 開始組裝數(shù)據(jù)
values.put(MySQLiteOpenHelper.PERSON_ID,person.getUserId());
values.put(MySQLiteOpenHelper.PERSON_NAME,person.getNickName());
values.put(MySQLiteOpenHelper.PERSON_PORTRAIT,person.getAvatarreName());
//id 返回的是數(shù)據(jù)的 id,如果返回 - 1 時(shí)表示未添加成功
long id=db.insert(MySQLiteOpenHelper.TABLE_NAME,null,values);// 插入數(shù)據(jù)
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;
}
/* 根據(jù)頁碼數(shù)目刪除信息 */
@Override
public int delete(String userId) {
SQLiteDatabase db=myDatabaseHelper.getWritableDatabase();
//i 返回的是刪除的是第幾行的數(shù)據(jù)檩互,返回 0 表示刪除不成功
int i = db.delete(MySQLiteOpenHelper.TABLE_NAME,
MySQLiteOpenHelper.PERSON_ID + "=?",new String[]{String.valueOf(userId)});
db.close();
//i 返回的是刪除的是第幾行的數(shù)據(jù),返回 0 表示刪除不成功
return i;
}
/* 根據(jù)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;
}
}
代碼以上。
最后程序運(yùn)行就可以顯示效果了薄风。
點(diǎn)擊不同的按鈕饵较,可分別對(duì)數(shù)據(jù)庫進(jìn)行不同的操作并輸出 Toast 提示和 LogCat 日志信息。