[Android] SQLite資料庫使用
阿新 • • 發佈:2018-12-02
SQLite簡介
SQLite是一個實現了自給自足的、無伺服器的、零配置的、事務性的SQL資料庫引擎,並且是一個開源專案。
Android上自帶SQLite,因此是Android專案上常用的資料庫。
一個簡單的demo通過SQLiteOpenHelper類實現了SQLite的增刪改查操作
Person.java
public class Person implements Serializable { //序列化的版本號 private static final long serialVersionUID = 1L; private int id; private String name; private int age; private String sex; public Person() { } public Person(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } public Person(int id, String name, int age, String sex) { this.id = id; this.name = name; this.age = age; this.sex = sex; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper { private static final String TAG = "SQLiteHelper"; //資料庫名 private static final String DATABASE_NAME = "mydb.db"; //資料庫 表名 public static final String PERSON_TABLE_NAME = "person"; public static final String USER_TABLE_NAME = "user"; public SQLiteHelper(Context context, int version) { super(context, DATABASE_NAME, null, version); } //建立資料庫 @Override public void onCreate(SQLiteDatabase db) { Log.e(TAG, "資料庫建立"); String sql1 = "create table if not exists " + PERSON_TABLE_NAME + "(id integer Primary Key autoincrement," + "name varchar(20)," + "age integer," + "sex varchar(20))"; String sql2 = "create table if not exists " + USER_TABLE_NAME + "(id integer Primary Key autoincrement," + "name varchar(20)," + "age integer," + "sex varchar(20))"; //執行sql語句 db.execSQL(sql1); db.execSQL(sql2); } //更新資料庫 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.e(TAG, "資料庫更新"); } //以下 增刪改查函式可以放到Activity中 //插入 public void insertPerson(Person person) { Log.e(TAG, "插入"); SQLiteDatabase db = getWritableDatabase(); String sql = "insert into " + PERSON_TABLE_NAME + "(name,age,sex) values(" + String.format("'%s'", person.getName()) + "," + person.getAge() + "," + String.format("'%s'", person.getSex()) + ");"; //插入資料庫 db.execSQL(sql); db.close(); } //更新 public void updatePerson(Person person) { Log.e(TAG, "更新"); SQLiteDatabase db = getWritableDatabase(); String sql = "update " + PERSON_TABLE_NAME + " set name = " + String.format("'%s'", person.getName()) + ",age = " + person.getAge() + ",sex = " + String.format("'%s'", person.getSex()) + "where id = " + person.getId(); db.execSQL(sql); db.close(); } //刪除 public void deletePersonById(int id) { Log.e(TAG, "刪除"); SQLiteDatabase db = getWritableDatabase(); String sql = "id = ?"; String wheres[] = {String.valueOf(id)}; db.delete(PERSON_TABLE_NAME, sql, wheres); db.close(); } //查詢所有 public List<Person> queryAllPerson() { List<Person> list = new ArrayList<>(); SQLiteDatabase db = getReadableDatabase(); String sql = "select * from " + PERSON_TABLE_NAME; Cursor cursor = db.rawQuery(sql, null); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); String sex = cursor.getString(cursor.getColumnIndex("sex")); Person person = new Person(); person.setId(id); person.setName(name); person.setAge(age); person.setSex(sex); list.add(person); } cursor.close(); db.close(); return list; } //根據id查詢 public Person queryPersonById(int id) { Person person = null; SQLiteDatabase db = getReadableDatabase(); String[] columns = {"id", "name", "age", "sex"}; String selection = "id = ?"; String[] selectionArgs = {String.valueOf(id)}; Cursor cursor = db.query(PERSON_TABLE_NAME, columns, selection, selectionArgs, null, null, null); if (cursor.moveToNext()) { person = new Person(); person.setId(cursor.getInt(cursor.getColumnIndex("id"))); person.setAge(cursor.getInt(cursor.getColumnIndex("age"))); person.setName(cursor.getString(cursor.getColumnIndex("name"))); person.setSex(cursor.getString(cursor.getColumnIndex("sex"))); } cursor.close(); db.close(); return person; } }
InsertDialog.java
public class InsertDialog extends Activity implements View.OnClickListener { //插入請求程式碼 大於0 private static final int INSERT_RESULTCODE = 11; //姓名控制元件 private EditText nameView; //年齡控制元件 private EditText ageView; //性別控制元件 private EditText sexView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //去掉標題欄 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_insert_dialog); nameView = (EditText) findViewById(R.id.insert_edit_name); ageView = (EditText) findViewById(R.id.insert_edit_age); sexView = (EditText) findViewById(R.id.insert_edit_sex); Button confirmBtn = (Button) findViewById(R.id.insert_confirm); Button cancelBtn = (Button) findViewById(R.id.insert_cancel); confirmBtn.setOnClickListener(this); cancelBtn.setOnClickListener(this); } private void confirm() { String name = String.valueOf(nameView.getText()); int age = Integer.valueOf(String.valueOf(ageView.getText())); String sex = String.valueOf(sexView.getText()); Person person = new Person(name, age, sex); Intent intent = new Intent(); intent.putExtra("person", person); setResult(INSERT_RESULTCODE, intent); finish(); } private void cancel() { setResult(INSERT_RESULTCODE); finish(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.insert_confirm: confirm(); break; case R.id.insert_cancel: cancel(); break; default: break; } } }
DeleteDialog.java
public class DeleteDialog extends Activity implements View.OnClickListener {
//插入請求程式碼
private static final int DELETE_RESULTCODE = 22;
//id控制元件
private EditText idView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_delete_dialog);
idView = (EditText) findViewById(R.id.delete_edit_id);
Button confirmBtn = (Button) findViewById(R.id.delete_confirm);
Button cancelBtn = (Button) findViewById(R.id.delete_cancel);
confirmBtn.setOnClickListener(this);
cancelBtn.setOnClickListener(this);
}
private void confirm() {
int id = Integer.valueOf(String.valueOf(idView.getText()));
Intent intent = new Intent();
intent.putExtra("id", id);
setResult(DELETE_RESULTCODE, intent);
finish();
}
private void cancel() {
setResult(DELETE_RESULTCODE);
finish();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete_confirm:
confirm();
break;
case R.id.delete_cancel:
cancel();
break;
default:
break;
}
}
}
UpdateDialog.java
public class UpdateDialog extends Activity implements View.OnClickListener {
//修改請求程式碼
private static final int UPDATE_RESULTCODE = 33;
//id控制元件
private EditText idView;
//姓名控制元件
private EditText nameView;
//年齡控制元件
private EditText ageView;
//性別控制元件
private EditText sexView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_update_dialog);
idView = (EditText) findViewById(R.id.update_edit_id);
nameView = (EditText) findViewById(R.id.update_edit_name);
ageView = (EditText) findViewById(R.id.update_edit_age);
sexView = (EditText) findViewById(R.id.update_edit_sex);
Button confirmBtn = (Button) findViewById(R.id.update_confirm);
Button cancelBtn = (Button) findViewById(R.id.update_cancel);
confirmBtn.setOnClickListener(this);
cancelBtn.setOnClickListener(this);
}
private void confirm() {
int id = Integer.valueOf(String.valueOf(idView.getText()));
String name = String.valueOf(nameView.getText());
int age = Integer.valueOf(String.valueOf(ageView.getText()));
String sex = String.valueOf(sexView.getText());
Person person = new Person(id, name, age, sex);
Intent intent = new Intent();
intent.putExtra("person", person);
setResult(UPDATE_RESULTCODE, intent);
finish();
}
private void cancel() {
setResult(UPDATE_RESULTCODE);
finish();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.update_confirm:
confirm();
break;
case R.id.update_cancel:
cancel();
break;
default:
break;
}
}
}
ListAdapter.java
public class ListAdapter extends BaseAdapter {
private List<Person> list;
private LayoutInflater inflater;
public ListAdapter(List<Person> list, Context context) {
this.list = list;
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setList(List<Person> list) {
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Person getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflater.inflate(R.layout.activity_main_list1, null);
TextView idView = (TextView) convertView.findViewById(R.id.text_id);
TextView nameView = (TextView) convertView.findViewById(R.id.text_name);
TextView ageView = (TextView) convertView.findViewById(R.id.text_age);
TextView sexView = (TextView) convertView.findViewById(R.id.text_sex);
Person person = list.get(position);
idView.setText(String.valueOf(person.getId()));
nameView.setText(person.getName());
ageView.setText(String.valueOf(person.getAge()));
sexView.setText(String.valueOf(person.getSex()));
return convertView;
}
}
MainActivity.java
/**
* SQLite 資料庫操作 增刪改查
*/
public class DBMainActivity extends AppCompatActivity implements View.OnClickListener {
private SQLiteHelper db;
private ListAdapter listAdapter;
private static final int INSERT_REQUESTCODE = 1;
private static final int INSERT_RESULTCODE = 11;
private static final int DELETE_REQUESTCODE = 2;
private static final int DELETE_RESULTCODE = 22;
private static final int UPDATE_REQUESTCODE = 3;
private static final int UPDATE_RESULTCODE = 33;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dbmain);
db = new SQLiteHelper(this, 1);
Button insertBtn = (Button) findViewById(R.id.btn_insert);
Button deleteBtn = (Button) findViewById(R.id.btn_delete);
Button updateBtn = (Button) findViewById(R.id.btn_update);
Button queryBtn = (Button) findViewById(R.id.btn_query);
insertBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
updateBtn.setOnClickListener(this);
queryBtn.setOnClickListener(this);
listAdapter = new ListAdapter(new ArrayList<Person>(), this);
ListView listView = (ListView) findViewById(R.id.list_data);
listView.setAdapter(listAdapter);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_insert:
insert();
break;
case R.id.btn_delete:
delete();
break;
case R.id.btn_update:
update();
break;
case R.id.btn_query:
query();
break;
default:
break;
}
}
private void insert() {
Intent intent = new Intent(this, InsertDialog.class);
startActivityForResult(intent, INSERT_REQUESTCODE);
}
private void delete() {
Intent intent = new Intent(this, DeleteDialog.class);
startActivityForResult(intent, DELETE_REQUESTCODE);
}
private void update() {
Intent intent = new Intent(this, UpdateDialog.class);
startActivityForResult(intent, UPDATE_REQUESTCODE);
}
private void query() {
List<Person> list = db.queryAllPerson();
loadData(list);
}
private void loadData(List<Person> list) {
listAdapter.setList(list);
listAdapter.notifyDataSetChanged();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case INSERT_REQUESTCODE:
if (resultCode == INSERT_RESULTCODE) {
if (data != null) {
db.insertPerson((Person) data.getSerializableExtra("person"));
Toast.makeText(this, "Insert Success!", Toast.LENGTH_SHORT).show();
query();
} else {
Toast.makeText(this, "Insert Cancel!", Toast.LENGTH_SHORT).show();
}
}
break;
case DELETE_REQUESTCODE:
if (resultCode == DELETE_RESULTCODE) {
if (data != null) {
int id = data.getIntExtra("id", -1);
if (id != -1) {
if (db.queryPersonById(id) != null) {
db.deletePersonById(id);
Toast.makeText(this, "Delete Success!", Toast.LENGTH_SHORT).show();
query();
} else {
Toast.makeText(this, "Delete Fail! id" + id + "not exist", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Delete Fail!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Delete Cancel!", Toast.LENGTH_SHORT).show();
}
}
break;
case UPDATE_REQUESTCODE:
if (resultCode == UPDATE_RESULTCODE) {
if (data != null) {
Person person = (Person) data.getSerializableExtra("person");
int id = person.getId();
if (db.queryPersonById(person.getId()) != null) {
db.updatePerson(person);
Toast.makeText(this, "Update Success!", Toast.LENGTH_SHORT).show();
query();
} else {
Toast.makeText(this, "Update Fail! id" + id + "not exist", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Update Cancel!", Toast.LENGTH_SHORT).show();
}
}
break;
default:
break;
}
}
}